Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

Line breaks are: \n for NewLine, and \r for Return carriage.

RegExp is fun, I advise learning more about it http://www.regular-expressions.info/ :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top