正则表达式帮助操纵字符串

use*_*070 5 php regex

我正在努力让我的头围绕正则表达式.

我有一个"iPhone:52.973053,-0.021447"

我想将冒号后的两个数字提取为两个单独的字符串,以逗号分隔.

谁能帮我?干杯

Bar*_*ers 7

尝试:

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);
Run Code Online (Sandbox Code Playgroud)

产生:

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
        )

)
Run Code Online (Sandbox Code Playgroud)

要不就:

preg_match('/\w+:\s*(-?\d+\.\d+),(-?\d+\.\d+)/',
    "iPhone: 52.973053,-0.021447",
    $match);
print_r($match);
Run Code Online (Sandbox Code Playgroud)

如果字符串只包含一个坐标.

一个小小的解释:

\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
Run Code Online (Sandbox Code Playgroud)


Fel*_*ing 2

不使用正则表达式的解决方案,使用explode()and stripos():) :

$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));
Run Code Online (Sandbox Code Playgroud)

假设字符串始终包含冒号。

或者,如果冒号之前的标识符仅包含字符(而不是数字),您也可以这样做:

$string = "iPhone: 52.973053,-0.021447";
$string  = trim($string, "a..zA..Z: ");
//$string = "52.973053,-0.021447"

$coordinates = explode(',', $string);
Run Code Online (Sandbox Code Playgroud)