0

I want to replace <br> with all its surrounding whitespaces with a linebreak \n and two whitespaces .

Here is an example of what I tried using regex:

preg_replace('#\s*<br>\s*#', "\n  ", "Der\n <br>      Hund");

I was expecting this:

enter image description here

But instead, I got this:

enter image description here

Which shows that <br> was replaced by two whitespaces, but not a line-break.

If I change the regex so that it does not match the whitespaces before the <br> it magically works:

preg_replace('#<br>\s*#', "\n  ", "Der\n <br>      Hund");

and I get as expected:

enter image description here

Why is the first regex not working as expected? I am using PHP 7.2.24.

Adam
  • 25,960
  • 22
  • 158
  • 247
  • `\s` matches line breaks. Do you mean you only want to match horizontal ones around `
    `? `'#\h*
    \h*#'` / `'#\h*
    \h*#u'`?
    – Wiktor Stribiżew May 10 '20 at 11:54
  • @WiktorStribiżew thank you so much. Now I get it :D. You want to post this as an aswer, or should I remove this question? – Adam May 10 '20 at 11:56
  • 1
    It has been answered before several times, I even had a very unpleasant feedback from other SO users when I answered a similar question, so let's close this one. – Wiktor Stribiżew May 10 '20 at 11:57

0 Answers0