Search code examples
phppreg-replace-callbacknl2br

PHP: add a linebreaks in a preg replace


I can understand most PHP code by just reading it, but I've never understood how preg_replace is used, so I've only been copying other peoples codes to get what I want.

Now I need to add linebreaks in it, and I've tried multiple combinations but I can't figure out how to use it.

This is my current code:

$textbr = nl2br($text);
$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($textbr)));

echo substr($output,0,870);
echo "...</p>";

So how would I add line breaks in this part of the code? I need it to both output the linebreak but then make the next letter a capitalized one.


Solution

  • To anyone wondering. I solved it by just randomly trying myself towards the solution.

    SOLUTION:

    $textbr = nl2br($text);
    $output = preg_replace_callback(
        '/([.!?\r?\n)])\s*(\w)/', 
        function ($matches) {
            return strtoupper($matches[1] . ' ' . $matches[2]);
        }, 
        ucfirst(
            strtolower($textbr)
        )
    );