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

时间:2010-04-06 13:46:52

标签: php regex

我正在努力想要了解正则表达式。

我有一个“iPhone:52.973053,-0.021447”

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

任何人都可以帮助我吗?干杯

6 个答案:

答案 0 :(得分: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);

产生:

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
        )

)

或者只是:

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

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

一个小小的解释:

\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

答案 1 :(得分:2)

不使用正则表达式的解决方案,使用explode()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));

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

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

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

$coordinates = explode(',', $string);

答案 2 :(得分:0)

尝试:

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

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

答案 3 :(得分:0)

我喜欢@Felix的非正则表达式解决方案,我认为他的问题解决方案比使用正则表达式更清晰,更易读。

如果更改了原始字符串格式,请不要忘记您可以使用常量/变量来更改逗号或冒号的拆分。

这样的东西
define('COORDINATE_SEPARATOR',',');
define('DEVICE_AND_COORDINATES_SEPARATOR',':');

答案 4 :(得分:0)

$str="iPhone: 52.973053,-0.021447";
$s = array_filter(preg_split("/[a-zA-Z:,]/",$str) );
print_r($s);

答案 5 :(得分:0)

更简单的解决方案是使用preg_split()和更简单的正则表达式,例如。

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

会给你

Array 
(
    [0] => iPhone:
    [1] => 52.973053
    [2] => -0.021447
)
相关问题