删除<p>块</p>中的换行符

时间:2012-02-01 15:31:59

标签: php regex

我有一个这样的字符串:

<p>Here some text
another line</p>

<p>Another paragraph
another line</p>

我想要的是以下内容:

<p>Here some text another line</p>

<p>Another paragraph another line</p>

基本上我想从段落标签中的字符串中删除新行字符而不是其他任何地方。

请帮忙。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您想使用preg_replace。

$string = "<p>Here some text
another line</p>

<p>Another paragraph
another line</p>


<p>test



123</p>
blah";
$pattern = '/<p>([^\n]+)\n+([^\n]+)/iS';
$replacement = "<p>$1 $2";

$paragraphs = explode("</p>",$string);

for ($i = 0; $i < count($paragraphs); $i++) {
    $paragraphs[$i] = preg_replace($pattern, $replacement, $paragraphs[$i]);
}

$string = implode("</p>", $paragraphs);

echo $string . "\n";

答案 1 :(得分:1)

devNoise,除非有多行\n,否则您的代码效果很好。我确信使用正则表达式比使用此处发布的更好的方法,但这里是:

    $string = "<p>Here some text
    another line</p>

    <p>Another paragraph
    another line</p>


    <p>test



    123</p>";

    $paragraphs = explode("</p>",$string);

    for ($i=0;$i<strlen($string);$i++) {
            if (strstr($string[$i].$string[$i+1].$string[$i+2],"<p>")) {
                    $replace_on = 1;
            }

            if (strstr($string[$i].$string[$i+1].$string[$i+2].$string[$i+3],"</p>")) {
                    $replace_on = 0;
            }

            if ($replace_on==1) {
                    if (strstr($string[$i],"\n")) {
                            $new_string .= " ";
                    } else {
                            $new_string .= $string[$i];
                    }
            } else {
                    $new_string .= $string[$i];
            }
    }

    echo $new_string;

答案 2 :(得分:1)

这应该做你想要的:

如果文字只包含段落

$string = "<p>Here some text
another line</p>

<p>Another paragraph
another line</p>";

$output = '';

$paragraphs = array_filter(explode("</p>", $string));

foreach ($paragraphs as $block) {
    $output .= str_replace(array("\r", "\n"), '', $block);       
}

var_dump($output); //<p>Here some textanother line</p><p>Another paragraphanother line</p>

如果文字包含多个标签

$string = "<p>Here some text 

another line</p>

<img src=\"/path/to/file.jpg\";

<div id=\"test\"> 
   <p>Another paragraph 



another line</p>
</div>";

preg_match_all('~<p>(.+?)</p>~si', $string, $paragraphs);

foreach ($paragraphs[0] as $block) {
    $output = '';

    if (strlen($block)) {
        $output = str_replace(array("\r","\n"), '', $block);
        $string = str_replace($block, $output, $string);
    }
}