New line to paragraph function

前端 未结 7 1049
情话喂你
情话喂你 2021-01-31 09:20

I have this interesting function that I\'m using to create new lines into paragraphs. I\'m using it instead of the nl2br() function, as it outputs better formatted

相关标签:
7条回答
  • 2021-01-31 09:55

    Here is another approach that doesn't use regular expressions. Note, this function will remove any single line-breaks.

    function nl2p($string)
    {
        $paragraphs = '';
    
        foreach (explode("\n", $string) as $line) {
            if (trim($line)) {
                $paragraphs .= '<p>' . $line . '</p>';
            }
        }
    
        return $paragraphs;
    }
    

    If you only need to do this once in your app and don't want to create a function, it can easily be done inline:

    <?php foreach (explode("\n", $string) as $line): ?>
        <?php if (trim($line)): ?>
            <p><?=$line?></p>
        <?php endif ?>
    <?php endforeach ?>
    
    0 讨论(0)
提交回复
热议问题