Php 正则表达式和preg_match_all的问题

Php 正则表达式和preg_match_all的问题,php,regex,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); 但它不起作用。任何人都可以帮我吗?你应该使用*?来减少贪婪。否则,它可能会匹配太长的子字

我也有一根很长的绳子:

$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);

但它不起作用。任何人都可以帮我吗?

你应该使用
*?
来减少贪婪。否则,它可能会匹配太长的子字符串。在您的案例中,有时使用否定字符类,
([^[\]]*)
也很有用

但最好是对你想要的东西特别明确:

preg_match_all("#\[([\d,.]+)]#", $text, $matches);
这样,它将只匹配\小数、逗号和点。哦,需要转义开头的
[

preg_match_all("#\[([\d.]+),([\d.]+)]#", $text, $matches, PREG_SET_ORDER);
将已经为您提供分开的X和Y坐标。请尝试将
PREG\u SET\u 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
        )

您需要将星号设置为“懒惰”:

但是这个怎么样

$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
        //...
)
这应该做到:

$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"
regexp的细分:

,?        // 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
  );
}

非常感谢!我刚刚意识到数组是二维的。我在回显$matches[1]时不断收到错误“array”。$matches[1][0]效果更好,现在只需构建循环。再次感谢!问题已修复
$coords = array();
foreach ($matches[1] as $match) {
  list($x, y) = explode(',', $match);
  $coords[] = array(
     'x' => (float)$x,
     'y' => (float)$y
  );
}