[英]PHP substr but keep HTML tags?
我想知道是否有一种优雅的方式来修剪一些文本但是在识别HTML标签的同时?
例如,我有这个字符串:
$data = '<strong>some title text here that could get very long</strong>';
并且假设我需要在页面上返回/输出此字符串,但希望它不超过X个字符。 让我们说35这个例子。
然后我用:
$output = substr($data,0,20);
但现在我最终得到:
<strong>some title text here that
正如您所看到的那样,关闭强标签将被丢弃,从而打破HTML显示。
有没有解决的办法? 另请注意,可以在字符串中包含多个标记,例如:
<p>some text here <strong>and here</strong></p>
几个mounths之前我创建了一个特殊功能,它可以解决您的问题。
这是一个功能:
function substr_close_tags($code, $limit = 300)
{
if ( strlen($code) <= $limit )
{
return $code;
}
$html = substr($code, 0, $limit);
preg_match_all ( "#<([a-zA-Z]+)#", $html, $result );
foreach($result[1] AS $key => $value)
{
if ( strtolower($value) == 'br' )
{
unset($result[1][$key]);
}
}
$openedtags = $result[1];
preg_match_all ( "#</([a-zA-Z]+)>#iU", $html, $result );
$closedtags = $result[1];
foreach($closedtags AS $key => $value)
{
if ( ($k = array_search($value, $openedtags)) === FALSE )
{
continue;
}
else
{
unset($openedtags[$k]);
}
}
if ( empty($openedtags) )
{
if ( strpos($code, ' ', $limit) == $limit )
{
return $html."...";
}
else
{
return substr($code, 0, strpos($code, ' ', $limit))."...";
}
}
$position = 0;
$close_tag = '';
foreach($openedtags AS $key => $value)
{
$p = strpos($code, ('</'.$value.'>'), $limit);
if ( $p === FALSE )
{
$code .= ('</'.$value.'>');
}
else if ( $p > $position )
{
$close_tag = '</'.$value.'>';
$position = $p;
}
}
if ( $position == 0 )
{
return $code;
}
return substr($code, 0, $position).$close_tag."...";
}
这是演示: http : //sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201 (单击“执行代码”以检查其工作原理)。
使用@newbieuser他的功能,我有同样的问题,如@巴勃罗-帕索斯,这是(不)(在我的情况时突破极限$掉进一个html标签<br />
在R)
修复了一些代码
if ( strlen($code) <= $limit ){
return $code;
}
$html = substr($code, 0, $limit);
//We must find a . or > or space so we are sure not being in a html-tag!
//In my case there are only <br>
//If you have more tags, or html formatted text, you must do a little more and also use something like http://htmlpurifier.org/demo.php
$_find_last_char = strrpos($html, ".")+1;
if($_find_last_char > $limit/3*2){
$html_break = $_find_last_char;
}else{
$_find_last_char = strrpos($html, ">")+1;
if($_find_last_char > $limit/3*2){
$html_break = $_find_last_char;
}else{
$html_break = strrpos($html, " ");
}
}
$html = substr($html, 0, $html_break);
preg_match_all ( "#<([a-zA-Z]+)#", $html, $result );
......
substr(strip_tags($ content),0,100)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.