2 回答
TA贡献1818条经验 获得超3个赞
$
将与行尾匹配的锚点(使用 m 修饰符)更改为\z
锚点(无论修饰符如何匹配字符串的末尾)。
这样,不情愿的量词.*?
将能够匹配多行,而不是停在行的第一端。
要在同一行中查找多个匹配项,请\s+
在数字前添加前瞻。否则数字之前的空间不能被消耗两次(一次被.*?
一次被 消耗一次(\s|^)
)。
~(\s|^)\d{1,3}/+\s.*?(?=\s+\d{1,3}/+\s|\z)~ms
请注意,您可以使用以下方法获得修剪结果:
~(?<!\S)\d{1,3}/+\s.*?(?=\s+\d{1,3}/+\s|\s*\z)~s
要减少步骤数,您可以更改\s.*?
并(?>\s+\S+)*?
删除不再需要的 s 修饰符。
TA贡献1802条经验 获得超6个赞
尝试:
(?:\s|^)\d{1,3}\/\s(?:(?!\s\d{1,3}\/\s)[\s\S])*
<?php
$str = "1/ This is a string and it
has some text on a new line
2/ And then there's another string that has text only on one line
532/ Another string that has some year on a new line
2020/xyz followed by some letters
720/ This is a match on the same line with another match but the other match won't be captured 721/ And this is the last line";
preg_match_all('/(?:\s|^)\d{1,3}\/\s(?:(?!\s\d{1,3}\/\s)[\s\S])*/', $str, $matches, PREG_SET_ORDER);
print_r($matches);
印刷:
Array
(
[0] => Array
(
[0] => 1/ This is a string and it
has some text on a new line
)
[1] => Array
(
[0] =>
2/ And then there's another string that has text only on one line
)
[2] => Array
(
[0] =>
532/ Another string that has some year on a new line
2020/xyz followed by some letters
)
[3] => Array
(
[0] =>
720/ This is a match on the same line with another match but the other match won't be captured
)
[4] => Array
(
[0] => 721/ And this is the last line
)
)
- 2 回答
- 0 关注
- 264 浏览
添加回答
举报