PHP substr但保留HTML标签?

20 php substr

我想知道是否有一种优雅的方式来修剪一些文本但是在识别HTML标签的同时?

例如,我有这个字符串:

$data = '<strong>some title text here that could get very long</strong>';
Run Code Online (Sandbox Code Playgroud)

并且假设我需要在页面上返回/输出此字符串,但希望它不超过X个字符.让我们说35这个例子.

然后我用:

$output = substr($data,0,20);
Run Code Online (Sandbox Code Playgroud)

但现在我最终得到:

<strong>some title text here that 
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,关闭强标签将被丢弃,从而打破HTML显示.

有没有解决的办法?另请注意,可以在字符串中包含多个标记,例如:

<p>some text here <strong>and here</strong></p>
Run Code Online (Sandbox Code Playgroud)

小智 5

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

这是一个函数:

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."...";
}
Run Code Online (Sandbox Code Playgroud)

这是DEMO:http : //sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201(单击“执行代码”以检查其工作方式)。


小智 -4

substr(strip_tags($内容), 0, 100)

  • 他想保留标签……而不是删除它们。 (3认同)