2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
$
將與行尾匹配的錨點(diǎn)(使用 m 修飾符)更改為\z
錨點(diǎn)(無(wú)論修飾符如何匹配字符串的末尾)。
這樣,不情愿的量詞.*?
將能夠匹配多行,而不是停在行的第一端。
要在同一行中查找多個(gè)匹配項(xiàng),請(qǐng)\s+
在數(shù)字前添加前瞻。否則數(shù)字之前的空間不能被消耗兩次(一次被.*?
一次被 消耗一次(\s|^)
)。
~(\s|^)\d{1,3}/+\s.*?(?=\s+\d{1,3}/+\s|\z)~ms
請(qǐng)注意,您可以使用以下方法獲得修剪結(jié)果:
~(?<!\S)\d{1,3}/+\s.*?(?=\s+\d{1,3}/+\s|\s*\z)~s
要減少步驟數(shù),您可以更改\s.*?
并(?>\s+\S+)*?
刪除不再需要的 s 修飾符。

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試:
(?:\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 關(guān)注
- 349 瀏覽
添加回答
舉報(bào)