i ciddiye regex etrafında başımı almak için mücadele ediyorum.
Ben bir Sring var "iPhone: 52.973053, -0,021447"
ben çok virgülle ayrılmış iki ayrı dizeleri içine kolon sonra iki sayı ayıklamak istiyorum.
Herkes bana yardımcı olabilir misiniz? Şerefe
Düzenli ifadeler kullanarak kullanmadan bir çözüm explode() and stripos() a> :):
$string = "iPhone: 52.973053,-0.021447";
$coordinates = explode(',', $string);
// $coordinates[0] = "iPhone: 52.973053"
// $coordinates[1] = "-0.021447"
$coordinates[0] = trim(substr($coordinates[0], stripos($coordinates[0], ':') +1));
Dize her bir kolon içerdiğini varsayarsak.
Kolon önce tanımlayıcı tek karakterleri (sayılar) içeriyorsa, ya da bunu yapabilirsiniz:
$string = "iPhone: 52.973053,-0.021447";
$string = trim($string, "a..zA..Z: ");
//$string = "52.973053,-0.021447"
$coordinates = explode(',', $string);
Deneyin:
preg_match_all('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/',
"iPhone: 52.973053,-0.021447 FOO: -1.0,-1.0",
$matches, PREG_SET_ORDER);
print_r($matches);
üretir:
Array
(
[0] => Array
(
[0] => iPhone: 52.973053,-0.021447
[1] => 52.973053
[2] => -0.021447
)
[1] => Array
(
[0] => FOO: -1.0,-1.0
[1] => -1.0
[2] => -1.0
)
)
Ya da sadece:
preg_match('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/',
"iPhone: 52.973053,-0.021447",
$match);
print_r($match);
dize yalnızca varsa bir koordinat.
Küçük bir açıklama:
\w+ # match a word character: [a-zA-Z_0-9] and repeat it one or more times
: # match the character ':'
\s* # match a whitespace character: [ \t\n\x0B\f\r] and repeat it zero or more times
( # start capture group 1
-? # match the character '-' and match it once or none at all
\d+ # match a digit: [0-9] and repeat it one or more times
\. # match the character '.'
\d+ # match a digit: [0-9] and repeat it one or more times
) # end capture group 1
, # match the character ','
( # start capture group 2
-? # match the character '-' and match it once or none at all
\d+ # match a digit: [0-9] and repeat it one or more times
\. # match the character '.'
\d+ # match a digit: [0-9] and repeat it one or more times
) # end capture group 2
Ben Felix'in olmayan regex çözüm @ seviyorum, ben sorun için onun çözümü bir regex kullanarak daha net ve okunabilir olduğunu düşünüyorum.
Orijinal dize biçimi değişti eğer virgül veya iki nokta üst üste ile bölme değiştirmek için sabitler / değişkenler kullanabilirsiniz unutmayın.
Gibi bir şey
define('COORDINATE_SEPARATOR',',');
define('DEVICE_AND_COORDINATES_SEPARATOR',':');