我想知道是否有一种优雅的方法来裁剪一些文本,同时又能识别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>
发布于 2015-12-27 16:43:10
几个月前,我创建了一个特殊的函数来解决你的问题。
下面是一个函数:
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 (点击“执行代码”来检查它是如何工作的)。
发布于 2017-11-14 20:14:51
使用@newbieuser他的函数时,我遇到了同样的问题,就像@pablo-pazos一样,当$limit掉进一个html标签(在我的例子中是r处的<br />
)时,它是(不)中断的。
使用一些代码进行了修复
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 );
......
发布于 2014-02-18 13:28:05
substr(strip_tags($content),0,100)
https://stackoverflow.com/questions/8933491
复制相似问题