正则表达式和preg_match_all的问题

时间:2011-03-17 17:50:12

标签: php regex

我也有一个非常长的字符串:

$text = "[23,64.2],[25.2,59.8],[25.6,60],[24,51.2],[24,65.2],[3.4,63.4]";

他们是坐标。我想从[] s中提取每个x,y 我真的很讨厌正则表达式,我仍然有问题写得正确

我试过

$pattern = "#\[(.*)\]#";
preg_match_all($pattern, $text, $matches);

但它没有用。有人可以帮我吗?

3 个答案:

答案 0 :(得分:0)

你应该使用.*?来减少贪婪。否则它可能匹配太长的子串。在你的情况下使用否定的字符类([^[\]]*)有时也很有帮助。

但最好还是要特别关注你想要的东西:

preg_match_all("#\[([\d,.]+)]#", $text, $matches);

这样它只会匹配 \ d ecimals和逗号和点。糟糕,开场[需要转义。

preg_match_all("#\[([\d.]+),([\d.]+)]#", $text, $matches, PREG_SET_ORDER);

已经给你分开的X和Y坐标了。另请尝试PREG_SET_ORDER作为第四个参数,它将为您提供:

Array
(
    [0] => Array
        (
            [0] => [23,64.2]
            [1] => 23
            [2] => 64.2
        )

    [1] => Array
        (
            [0] => [25.2,59.8]
            [1] => 25.2
            [2] => 59.8
        )

    [2] => Array
        (
            [0] => [25.6,60]
            [1] => 25.6
            [2] => 60
        )

答案 1 :(得分:0)

你需要让星号“懒惰”:

$pattern = "#\[(.*?)\]#";

但是这个怎么样?

$pattern = "#\[(\d+(\.\d+)?),(\d+(\.\d+)?)\]#";

在您的代码中,这将产生

Array
(
    [0] => Array
        // ...

    [1] => Array
        (
            [0] => 23
            [1] => 25.2
            [2] => 25.6
            [3] => 24
            [4] => 24
            [5] => 3.4
        )

    [2] => Array
        //...

    [3] => Array
        (
            [0] => 64.2
            [1] => 59.8
            [2] => 60
            [3] => 51.2
            [4] => 65.2
            [5] => 63.4
        )

    [4] => Array
        //...
)

答案 2 :(得分:0)

这应该这样做:

$string = '[23,64.2],[25.2,59.8],[25.6,60],[24,51.2],[24,65.2],[3.4,63.4]';
if (preg_match_all('/,?\[([^\]]+)\]/', $string, $matches)) {
  print_r($matches[1]);
}

打印:

[0] => string(7) "23,64.2"
[1] => string(9) "25.2,59.8"
[2] => string(7) "25.6,60"
[3] => string(7) "24,51.2"
[4] => string(7) "24,65.2"
[5] => string(8) "3.4,63.4"

正则表达式的细分:

,?        // zero or one comma
\[        // opening bracket
([^\]]+)  // capture one or more chars until closing bracket
\]        // closing bracket

要获得x,y坐标,您可以:

$coords = array();
foreach ($matches[1] as $match) {
  list($x, y) = explode(',', $match);
  $coords[] = array(
     'x' => (float)$x,
     'y' => (float)$y
  );
}