如何从HTML标签读取CDATA
以下是php中的函数,它接受任何字符串(字符串也包含html标签),并从变量$ min中提到的字符中返回几个字。如何从HTML标签读取CDATA
function gen_string($string,$min=500,$clean=true) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
$query = "select distinct ID from cms_content";
$result = mysql_query($query);
$IDlink = 'http://localhost/www/index.php?ID='.$result;
if(strlen($text)>=$max && !$clean) $r=trim($r,'.') ;
} else {
# if there are no spaces
$r = substr($text,0,$min).'.........';
}
} else {
# if original length is lower than limit
$r = $text;
}
return trim($r);
}
但问题是,在返回的字符串中,它不会读取html标记。 那么如何让这个函数读取html标签,以便返回的字符串必须在格式化的html标签中?
你的问题是这样的:
$text = trim(strip_tags($string));
strip_tags
将删除所有的标签,从而使功能不可能返回任何。
由于您正在剪切部分字符串,因此最终会生成无效的HTML片段。您需要tidy
或HTMLPurifier
以解决此问题。
使用tidy构造有效的(X)HTML字符串,它解析为DOM document,然后使用XPath(未经测试)//body//text()
。
我已经指出你正确的功能/类的方法,所以你可以打地面运行。
文档和用户注释可能对您特别有用。
POC:
1 <?php
2 $string = '<p>Hello <b>World <i>out</i><span>there</span></b></p>';
3
4 $string = tidy_repair_string($string);
5
6 $doc = new DOMDocument;
7 $doc->loadHTML($string);
8
9 $path = new DOMXPath($doc);
10
11 $entries = $path->query('//body//text()');
12
13 $string = NULL;
14
15 foreach($entries as $entry) {
16 if(preg_match('/\w/', $entry->nodeValue)) {
17 $string .= $entry->nodeValue;
18 }
19 }
20 echo $string;
输出:Hello World outthere
。
我试图让我的功能适合文档示例,但不能得到这个... :( – 2012-01-01 09:10:02
我也试过这个,但没有工作http://css-tricks.com/snippets/ php/truncate-strings/ – 2012-01-01 09:10:56
嗯,我的答案表明你用这种新方法重写你的函数。 – Flavius 2012-01-01 09:11:52
不错的问题,+1 – Flavius 2012-01-01 08:28:59