PHP substr但保留HTML标签?

时间:2012-01-19 21:24:55

标签: php substr

我想知道是否有一种优雅的方式来修剪一些文本但是在识别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>

3 个答案:

答案 0 :(得分:4)

几个前我创建了一个特殊功能,可以解决您的问题。

这是一个功能:

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."...";
}

以下是DEMO:http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201(点击&#34;执行代码&#34;检查其工作原理)。

答案 1 :(得分:0)

使用@newbieuser他的功能,我有同样的问题,比如@ pablo-pazos,当$ limit落入一个html标签(在我的情况下,<br />在r)时,它(不)中断了< / p>

修正了一些代码

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 );
......

答案 2 :(得分:-3)

substr(strip_tags($ content),0,100)