Opposite of nl2br? Is it str_replace?

后端 未结 8 1613
旧时难觅i
旧时难觅i 2020-12-02 00:07

So the function nl2br is handy. Except in my web app, I want to do the opposite, interpret line breaks as new lines, since they will be echoed into a pre-filled form.

<
相关标签:
8条回答
  • 2020-12-02 00:59

    You can use br2nl() for nl2br() reversal.

    0 讨论(0)
  • 2020-12-02 01:07

    There will probably be some situations where your code is not enough ; so, what about something like this, to do your replacement :

    $html = 'this <br>is<br/>some<br />text <br    />!';
    $nl = preg_replace('#<br\s*/?>#i', "\n", $html);
    echo $nl;
    

    i.e. a bit more complex than a simple str_replace ;-)

    Note : I would generally say don't use regex to manipulate HTML -- but, in this case, considering the regex would be pretty simple, I suppose it would be OK.


    Also, note that I used "\n"

    • i.e. a newline : \n
    • in a double-quoted string, so it's interpreted as a newline, and not a literal \n


    Basically, a <br> tag generally looks like :

    • <br>
    • or <br/>, with any number of spaces before the /

    And that second point is where str_replace is not enough.

    0 讨论(0)
提交回复
热议问题