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 關注
- 325 瀏覽
添加回答
舉報