PHP 使用正则表达式匹配新行中的所有字符

PHP Match All Character in New Line with Regex

我想匹配 [nextpage] bbcode 之后的任何字符,但是下面的 bbcode 不匹配我换行时后面的文本。

$string="[nextpage] This is how i decided to make a living with my laptop.
This doesn't prevent me from doing some chores,

I get many people who visits me on a daily basis.

[nextpage] This is the second method which i think should be considered before taking any steps.

That way does not stop your from excelling. I rest my case.";

$pattern="/\[nextpage\]([^\r\n]*)(\n|\r\n?|$)/is";
preg_match_all($pattern,$string,$matches);
$totalpages=count($matches[0]);
$string = preg_replace_callback("$pattern", function ($submatch) use($totalpages) { 
$textonthispage=$submatch[1];
return "<li> $textonthispage";
}, $string);
echo $string;

这只是 returns 第一行的文字。

<li> This is how i decided to make a living with my laptop.

<li> This is the second method which i think should be considered before taking any steps.

预期结果;

<li> This is how i decided to make a living with my laptop.
This doesn't prevent me from doing some chores,

I get many people who visits me on a daily basis.

<li> This is the second method which i think should be considered before taking any steps.

That way does not stop your from excelling. I rest my case.

您可以使用此正则表达式进行搜索:

\[nextpage]\h*(?s)(.+?)(?=\[nextpage]|\z)

替换为:

<li>

RegEx Demo

PHP代码:

$re = '/\[nextpage]\h*(?s)(.+?)(?=\[nextpage]|\z)/';
$result = preg_replace($re, '<li>', $str);

Code Demo

正则表达式分解:

\[nextpage]         # match literal text "[nextpage]"
\h*                 # match 0+ horizontal whitespaces
(?s)(.+?)           # match 1+ any characters including newlines
(?=\[nextpage]|\z)  # lookahead to assert that we have another "[nextpage]" or end of text

如果您有固定字符串,则不应使用正则表达式。正则表达式很昂贵,一个简单的 str_replace 也可以解决问题:

$result = str_replace("[nextpage]", "<li>", $str);

如果你想要它是正确的HTML,你还需要一个关闭标签:

$result = str_replace("[nextpage]", "</li><li>", $string);
$result = substr($result, 5, strlen($result)).'</li>'; // remove the start </li>

echo $result;