解析网页文本内容并在<div>中以相同的形式查看</div>

时间:2013-09-30 18:00:56

标签: php regex html

这里我正在解析页面文本:

<?php
$url= 'http://www.paulgraham.com/herd.html';
$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));

echo $test; //This gives entire content in one line loosing actual page text format
echo echo nl2br($textContent);  // This does not show in single line but some un usual form. 

?>

我也尝试使用<pre>标记,但它也以单行显示整个内容。 这里有什么变化,以便我可以在原始页面中获得带有断行的段落?

我只希望文字内容没有图片,按钮等等。

1 个答案:

答案 0 :(得分:1)

如果你更换了什么:

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

$test = preg_replace("/<br>/", "\r\n", html_entity_decode($text));
$test = preg_replace("/<.+?>/", " ", $test);
$test = preg_replace("/[^a-zA-Z\r\n]+/", " ", $test);