【问题标题】:Showing webpage content with newline character显示带有换行符的网页内容
【发布时间】:2013-09-30 10:30:43
【问题描述】:

我解析网页内容并通过以下方式将其显示在 div 中:

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTMLFile($url);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
foreach($xpath->query("//script") as $script) {
    $script->parentNode->removeChild($script);
}

$textContent = $doc->textContent; //inherited from DOMNode
$text=escapeshellarg($textContent);

$test = preg_replace("/[^a-zA-Z]+/", " ", html_entity_decode($text));

但这也会将换行符(段落)删除到 $test 中。 如何在上面包含换行符,以便每个段落都可见?

【问题讨论】:

    标签: php regex newline


    【解决方案1】:

    您可以简单地通过不替换它们来包含换行符。

    $test = preg_replace("/[^a-zA-Z\n]+/", " ", html_entity_decode($text));
                                   ^^
    

    【讨论】:

      【解决方案2】:

      PHP 有一个很好的功能。试试这个:

      echo nl2br($test);
      

      【讨论】:

      • 谢谢,但它会跳过换行符。这是我的代码审查,请codetidy.com/6796
      猜你喜欢
      • 2015-09-07
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 2016-05-18
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多