0

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.

jleft
  • 3,457
  • 1
  • 23
  • 35
saknar namn
  • 139
  • 1
  • 1
  • 10
  • You haven`t described what you are trying to do with the code you pasted. Have you tried to add "\n" for linebrake? – Oskars Pakers Apr 07 '14 at 08:35
  • i described what i needed help with. "I've never understood how preg_replace is used" "Now I need to add linebreaks in it, and I've tried multiple combinations but I can't figure out how to use it." – saknar namn Apr 07 '14 at 09:17

2 Answers2

0

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/ :)

Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • so how do i add it into that preg_replace? i tried some combinations, but i didnt have any luck – saknar namn Apr 07 '14 at 09:18
  • please post an expected result so I could better know what it is you need to accomplish. – Unamata Sanatarai Apr 07 '14 at 09:26
  • input: "hi, my name is bla bla and i like carrots. this is an orange text. LINEBREAK LINEBREAK this is just a test line" and it should capitalize "hi" "this" x2. the text should look like this http://i.imgur.com/EckFtGB.png but the first letter after the linebreaks doesnt capitalize. which i need it to do – saknar namn Apr 07 '14 at 09:46
0

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)
    )
);
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
saknar namn
  • 139
  • 1
  • 1
  • 10