Opposite of nl2br? Is it str_replace?

后端 未结 8 1612
旧时难觅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:44
        <?php echo strip_tags('Dear<br/>Bidibidi'); ?>
        Dear
        Bidibidi
    
        <?php echo nl2br('Dear
                    Bidibidi'); ?>
        Dear<br/>Bidibidi
    

    http://php.net/manual/tr/function.strip-tags.php

    0 讨论(0)
  • 2020-12-02 00:48

    I just skipped nl2br() and used this in another way like this:

    $post_content  = str_replace('\n',"<br />",$post_content );
    

    and all works fine.

    For complete description, please visit to my blog, here:

    How to use nl2br and reverse br2nl

    0 讨论(0)
  • 2020-12-02 00:55

    An alternative to @PascalMARTIN 's answer:

    $string = str_replace(array(
        '<br>',
        '<br/>',
        '<br />',
    ), "\n", $string);
    

    It does not work with multiple white-spaces like <br /> but this should be a really rare case.

    0 讨论(0)
  • 2020-12-02 00:56

    If whitespaces are stripped out before outputting the html (for minification), "\n", "\r", PHP_EOL, etc. will get stripped out. ASCII encoding will survive the stripping process.

    function minify($buffer) {
        return preg_replace('/\s\s+/', ' ', preg_replace('~>\s+<~', '><', $buffer));
    }
    ob_start('minify');
    
    ...
    
    $nl = preg_replace('/\<br(\s*)?\/?\>/i', "&#10;", $br);
    echo "<textarea>{$nl}</textarea>";
    
    ...
    
    ob_get_flush();
    
    0 讨论(0)
  • 2020-12-02 00:57

    You'd want this:

    <?=str_replace('<br />',"\n",$foo)?>
    

    You probably forgot to use double quotes. Strings are only parsed for special characters if you use double quotes.

    0 讨论(0)
  • 2020-12-02 00:58

    Are you writing '\n'? Because \n will only be interpreted correctly if you surround it with double quotes: "\n".

    Off topic: the <?= syntax is evil. Please don't use it for the sake of the other developers on your team.

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