[英]Problem with regex and preg_match_all
I have a very long string similar too : 我也有一个很长的字符串类似:
$text = "[23,64.2],[25.2,59.8],[25.6,60],[24,51.2],[24,65.2],[3.4,63.4]";
They are coordinates. 它们是坐标。 I'd like to extract every x,y from the []s I really hate regex, i still have problems to write it correctly 我想从我真的讨厌正则表达式的[]中提取每个x,y,但仍然存在正确编写它的问题
I tried 我试过了
$pattern = "#\[(.*)\]#";
preg_match_all($pattern, $text, $matches);
But it didn't work. 但这没有用。 Any one could help me please ? 有人可以帮我吗?
You should use .*?
您应该使用.*?
to make it less greedy. 减少贪婪 Otherwise it is likely to match too long substrings. 否则,它可能会匹配太长的子字符串。 It's also sometimes helpful to use a negated character class, ([^[\\]]*)
in your case. 在您的情况下,使用否定字符类([^[\\]]*)
有时也很有帮助。
But it's always best to be extra specific about what you want: 但是,始终最好对您想要的内容更加具体:
preg_match_all("#\[([\d,.]+)]#", $text, $matches);
This way it will only match \\d ecimals and commas and dots. 这样,它将仅匹配\\ d逗号,逗号和点。 Oops, and the opening [
needs to be escaped. 糟糕,并且[
需要逃脱。
preg_match_all("#\[([\d.]+),([\d.]+)]#", $text, $matches, PREG_SET_ORDER);
Would already give you the X and Y coordinates separated. 会给您X和Y坐标分开的。 Try also PREG_SET_ORDER
as fourth parameter, which will give you: 也尝试将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
)
You need to make the asterisk "lazy": 您需要使星号“懒惰”:
$pattern = "#\[(.*?)\]#";
But how about this? 但是呢?
$pattern = "#\[(\d+(\.\d+)?),(\d+(\.\d+)?)\]#";
On your code, this would produce 在您的代码上,这将产生
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
//...
)
This should do it: 应该这样做:
$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]);
}
It prints: 它打印:
[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"
A breakdown of the regexp: 正则表达式的分解:
,? // zero or one comma
\[ // opening bracket
([^\]]+) // capture one or more chars until closing bracket
\] // closing bracket
To get the x, y coordinates, you could then: 要获取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.