Search code examples
phpregexpreg-match-allpreg-replace-callback

PHP Match All Character in New Line with Regex


I want to match any character after [nextpage] bbcode but the below bbcode does not match texts that follow when i make a break line.

$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;

This only returns the texts in the first line.

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

Expected result;

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

Solution

  • You may search using this regex:

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

    Replace by:

    <li>$1
    

    RegEx Demo

    PHP Code:

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

    Code Demo

    RegEx Breakup:

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