[英]Multiline PHP Regex problem
I already tried looking here and in google... but I can't figure out what am I doing wrong :( 我已经尝试在这里和Google中查找...但是我不知道自己在做什么错了:(
I have this text: 我有这段文字:
C 1 title
comment 1
C 2 title2
comment 2
C 3 title3
comment 3
Now... What I want to do is 现在...我想做的是
I'm trying to use this expression: 我正在尝试使用以下表达式:
preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match);
but it only works for the first set =( 但仅适用于第一组=(
Any tip on what am I doing wrong??? 关于我在做什么错的任何提示???
Thanks!!!! 谢谢!!!!
It works as expected. 它按预期工作。
The snippet: 片段:
<?php
$body = 'C 1 title
comment 1
C 2 title2
comment 2
C 3 title3
comment 3';
preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match);
print_r($match);
?>
produces the following output: 产生以下输出:
Array
(
[0] => Array
(
[0] => C 1 title
comment 1
[1] => C 2 title2
comment 2
[2] => C 3 title3
comment 3
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => title
[1] => title2
[2] => title3
)
[3] => Array
(
[0] => comment 1
[1] => comment 2
[2] => comment 3
)
)
as you can see on Ideone . 正如您在Ideone上看到的那样 。
To keep your matches nicely grouped, you might want to try: 为了使您的比赛保持良好的分组,您可能需要尝试:
preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match, PREG_SET_ORDER);
instead. 代替。
HTH HTH
Ideone runs: PHP Version => 5.2.12-pl0-gentoo
Ideone运行:
PHP Version => 5.2.12-pl0-gentoo
And I also tested it on my machine (and get the same result), which runs: PHP Version => 5.3.3-1ubuntu9.5
我也在运行的机器上对其进行了测试(并得到相同的结果):
PHP Version => 5.3.3-1ubuntu9.5
But I can't imagine this is a versioning thing (at least, not with 5.x versions). 但是我无法想象这是一个版本控制的东西(至少不是在5.x版本中)。 Perhaps your line breaks are Windows style?
也许您的换行符是Windows风格的? Try this regex instead:
尝试使用此正则表达式:
"/^C +(\d*) +(.*)\r?\n(.*)$/im"
I used the line break \\r?\\n
instead of just \\n
so that Windows and Unix-style line breaks are matched, and also replaced single spaces with +
to account for possible two (or more) spaces. 我使用换行符
\\r?\\n
而不只是\\n
以便匹配Windows和Unix风格的换行符,并且还用+
替换了单个空格,以解决可能的两个(或更多)空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.