从标签中提取文本

时间:2009-10-23 10:47:03

标签: php

您好我在这里有这些行,我正在尝试提取文件中找到的第一段,但是这无法返回任何结果,如果不是,它会返回甚至不在<p>标签中的结果很奇怪?

$file = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];
$hd = fopen($file,'r');
$cn = fread($hd, filesize($file));
fclose($hd);

$cnc = preg_replace('/<p>(.+?)<\/p>/','$1',$cn);

2 个答案:

答案 0 :(得分:3)

我会使用DOM parsing

// SimpleHtmlDom example
// Create DOM from URL or file
$html = file_get_html('http://localhost/blah.php');

// Find all paragraphs 
foreach($html->find('p') as $element) 
       echo $element->innerText() . '<br>';

它可以让您更可靠地替换一些标记:

$html->find('p', 0)->innertext() = 'foo';

答案 1 :(得分:3)

试试这个:

$html = file_get_contents("http://localhost/foo.php");
preg_match('/<p>(.*)<\/p>/', $html, $match);
echo($match[1]);