繁体   English   中英

正则表达式和preg_match_all问题

[英]Problem with regex and preg_match_all

我也有一个很长的字符串类似:

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

它们是坐标。 我想从我真的讨厌正则表达式的[]中提取每个x,y,但仍然存在正确编写它的问题

我试过了

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

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

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

但是,始终最好对您想要的内容更加具体:

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

这样,它将仅匹配\\ d逗号,逗号和点。 糟糕,并且[需要逃脱。

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
        )

您需要使星号“懒惰”:

$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
        //...
)

应该这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM