使用正则表达式从字符串中删除额外的行

时间:2014-08-06 08:35:15

标签: php regex

我的字符串有这样的文字;

TEXT 1 GOES HERE

TEXT 2 GOES HERE

TEXT 3 GOES HERE

我希望它像这样;

TEXT 1 GOES HERE
TEXT 2 GOES HERE
TEXT 3 GOES HERE

我正在尝试此代码;

    $news_setting = str_replace('\n\n','\n',$news_settings);
    $news_array = explode("\n",$news_setting);
    foreach($news_array AS $news)
    {
        $news_bit .= '<div class="news_bit">'.$news.'</div>';
    }

但不幸的是,它没有删除任何额外的换行符。请帮忙!

2 个答案:

答案 0 :(得分:1)

试试这个:

    $news_setting = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $news_settings);
    $news_array = explode("\n",$news_setting);
    foreach($news_array AS $news)
    {
        $news_bit .= '<div class="news_bit">'.$news.'</div>';
    }

答案 1 :(得分:1)

试试这个

$text = "TEXT 1 GOES HERE

TEXT 2 GOES HERE

TEXT 3 GOES HERE";
$text = preg_replace("/[\r\n]+/", "\n", $text);
echo $text;