Dize işlenirken ile Regex Yardım

5 Cevap php

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

5 Cevap

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

Deneyin:

$string = "iPhone: 52.973053,-0.021447";

preg_match_all( "/-?\d+\.\d+/", $string, $result );
print_r( $result );

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',':');

Daha da basit bir çözüm, örneğin, çok daha basit bir düzenli ifade ile () preg_split kullanmaktır

$str   = 'iPhone: 52.973053,-0.021447';
$parts = preg_split('/[ ,]/', $str);
print_r($parts);

Sana verecek

Array 
(
    [0] => iPhone:
    [1] => 52.973053
    [2] => -0.021447
)