preg_match不会忽略新的换行符



任务:找到10个单词并忽略新的换行符。

我已经为multi-line添加了m标志,但它没有效果。

<?php
$string = "this is line onen this is line twon this is line threen";
$pattern = '/([A-Za-z0-9.]+ ){1,10}([A-Za-z0-9.]+)/m';
preg_match($pattern, $string, $matches);
echo $matches[0];
echo "n";
?>

结果:

this is line one

期望的结果 :

this is line one this is line two this is line

对于这个想要的结果,我只是手动删除了新的换行符。

虽然这个期望的结果也不是完美的......因为它总共是11个单词而不是10个单词。如果我走到这一步,我仍然会更接近我的使命。

我的猜测是,也许您正在尝试使用双界量词编写一些表达式,例如:

(?i)^(s*[a-z0-9. ]{1,10}(?=s|$)){0,4}$

演示 1

(?i)^(s*[a-z0-9. ]{1,10}(?=s|$)){0,5}

演示 2

(?i)(s*[a-z0-9. ]{1,10}(?=s|$)){0,5}

演示 3

(?:S+(?=s|$)s*){6}

演示 4

(?:S+s*){6}

演示 5

或者用于捕获前六个单词,例如,

^(?:(S+)s*)(?:(S+)s*)(?:(S+)s*)(?:(S+)s*)(?:(S+)s*)(?:(S+)s*)

演示 6

这是查找 10 个单词的正则表达式。
获取单个匹配项,然后使用空格加入组 1-10

(?s)(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S).*?(?<!S)([A-Za-z0-9.]+)(?!S)

https://regex101.com/r/g0Luco/1

最新更新