显示带换行符的网页内容

时间:2013-09-30 10:30:44

标签: php regex newline

我解析网页内容并以下列方式在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中。 如何在上面包含换行符,以便每个段落都可见?

2 个答案:

答案 0 :(得分:1)

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

echo nl2br($test);

答案 1 :(得分:1)

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

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