PHP substr但保留HTML标记? [英] PHP substr but keep HTML tags?

查看:103
本文介绍了PHP substr但保留HTML标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种优雅的方式来修剪某些文本,但又可以识别HTML标记?

I am wondering if there is an elegant way to trim some text but while being HTML tag aware?

例如,我有以下字符串:

For example, I have this string:

$data = '<strong>some title text here that could get very long</strong>';

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

And let's say I need to return/output this string on a page but would like it to be no more than X characters. Let's say 35 for this example.

然后我使用:

$output = substr($data,0,20);

但是现在我得到了:

<strong>some title text here that 

如您所见,最后的强标签被丢弃,从而破坏了HTML的显示.

which as you can see the closing strong tags are discarded thus breaking the HTML display.

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

Is there a way around this? Also note that it is possible to have multiple tags in the string for example:

<p>some text here <strong>and here</strong></p>

推荐答案

几年前,我创建了一个特殊的函数来解决您的问题.

A few mounths ago I created a special function which is solution for your problem.

这是一个功能:

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 点击执行代码"以检查其工作方式.)

Here is DEMO: http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201 (click "Execute code" to check how it works).

这篇关于PHP substr但保留HTML标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆