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

时间:2017-08-22 14:55:07

标签: php regex preg-match-all preg-replace-callback

我希望匹配[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;

这只返回第一行的文本。

<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.

2 个答案:

答案 0 :(得分:1)

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

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

替换为:

<li>$1

RegEx Demo

PHP代码:

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

Code Demo

RegEx分手:

\[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

答案 1 :(得分:0)

如果你有一个固定的字符串,你不应该正则表达式。正则表达式很昂贵,简单的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;