Php truncation of the content of an article with an html string

Source: Internet
Author: User
Tags chr html tags strlen tidy truncated

A blogger writes an article. The blog background usually provides the article title and truncated article part on the search page or list page as the entrance for further reading.

Function: mb_substr ($ str, $ start, $ length, $ encoding)

$ Str: string to be truncated
$ Start: truncation start
$ Length, length (note: This is different from mb_strimwidth. 1 represents a Chinese character)
$ Encoding, encoding, I set it to UTF-8

For example, the title of an article is truncated and 15 characters are allowed.

The code is as follows: Copy code

<? Php echo mb_substr ('www .111cn.net original', 0, 15, "UTF-8");?>

In this way, there is no problem with plain text, but my problem is that there are html tags in the middle. How to cut an article. Note: this article not only contains common string text, but also contains various texts that format tags and style content. If not properly handled, these closed tags cannot be properly closed, thus damaging the entire document flow.

If it is plain text, the following function is almost enough.

  

The code is as follows: Copy code
<? Php
/**
* String truncation, supporting Chinese and other encoding
     *
* @ Param string $ str string to be converted
* @ Param string $ start position
* @ Param string $ length truncation length
* @ Param string $ charset encoding format
* @ Param string $ suffix truncation string suffix
* @ Return string
*/
Function substr_ext ($ str, $ start = 0, $ length, $ charset = "UTF-8", $ suffix = "")
    {
If (function_exists ("mb_substr ")){
Return mb_substr ($ str, $ start, $ length, $ charset). $ suffix;
    }
Elseif (function_exists ('iconv _ substr ')){
Return iconv_substr ($ str, $ start, $ length, $ charset). $ suffix;
        }
$ Re ['utf-8'] = "/[x01-x7f] | [xc2-xdf] [x80-xbf] | [xe0-xef] [x80-xbf] {2} | [xf0-xff] [x80-xbf] {3 }/";
$ Re ['gb2312'] = "/[x01-x7f] | [xb0-xf7] [xa0-xfe]/";
$ Re ['gbk'] = "/[x01-x7f] | [x81-xfe] [x40-xfe]/";
$ Re ['big5'] = "/[x01-x7f] | [x81-xfe] ([x40-x7e] | xa1-xfe])/";
Preg_match_all ($ re [$ charset], $ str, $ match );
$ Slice = join ("", array_slice ($ match [0], $ start, $ length ));
Return $ slice. $ suffix;
    }


However, if you want to truncate a part of the formatted text in a webpage, the above functions are not enough. It does not support formatting tags.


In this case, a new function is required. It should be the upgraded enhanced version of the above function. It must be able to process tags correctly.

The strip_tags () function removes tags from HTML, XML, and PHP.

Example 1

The code is as follows: Copy code

<? Php
Echo strip_tags ("Hello <B> world! </B> ");
?>

Output:

Hello world!

In this way, we only need to perform the following operations on the basis of the above.

The code is as follows: Copy code

<? Php
$ A = strip_tags ("Hello <B> world! </B> ");
Substr_ext ($ a, 10 );

However, it is not a good solution if html is lost.
?>

Then google found that the system wrote a function that supports html string truncation.

The code is as follows: Copy code

/**
* Obtain the nth occurrence position of a character in the string.
* @ Param string $ text string
* @ Param string $ key
* @ Param int $ int N
* @ Return int
*/
Function strpos_int ($ text, $ key, $ int)
{
$ Keylen = strlen ($ key );
Global $ textlen;
If (! $ Textlen)
$ Textlen = strlen ($ text );
Static $ textpos = 0;
$ Pos = strpos ($ text, $ key );
$ Int --;
If ($ pos)
    {
If ($ int = 0)
$ Textpos + = $ pos;
Else
$ Textpos + = $ pos + $ keylen;
    }
Else
    {
$ Int = 0;
$ Textpos = $ textlen;
    }
If ($ int> 0)
    {
Strpos_int (substr ($ text, $ pos + $ keylen), $ key, $ int );
    }
Return $ textpos;
}

 

/**
* Intercept HTML
* @ Param string $ string HTML string
* @ Param int $ length: the length of the clip.
* @ Param string $ dot
* @ Param string $ append
* @ Return string
*/
Function cuthtml ($ string, $ length, $ dot = '...', $ append = "")
{
$ Str = strip_tags ($ string); // filter tags first
$ New_str = iconv_substr ($ str, 0, $ length, 'utf-8 ');
$ Last = iconv_substr ($ new_str,-1, 1, 'utf-8 ');
$ SC = substr_count ($ new_str, $ last );
$ Position = strpos_int ($ string, $ last, $ SC); // Obtain the extract length.
If (function_exists ('tidy _ parse_string ') // if tidy is enabled on the server, the html code of the function is incomplete.
    {
$ Options = array ("show-body-only" => true );
Return tidy_parse_string (mb_substr ($ string, 0, $ position). $ dot. $ append, $ options, 'utf8 ');
} Else // tidy is not enabled
    {
If (strlen ($ string) <= $ position)
        {
Return $ string;
        }

$ Pre = chr (1 );
$ End = chr (1 );
$ String = str_replace (array ('&', '"', '<', '>'), array ($ pre. '&'. $ end, $ pre. '"'. $ end, $ pre. '<'. $ end, $ pre. '> '. $ end), $ string );

$ Strcut = '';

$ N = $ tn = $ noc = 0;
While ($ n <strlen ($ string ))
        {

$ T = ord ($ string [$ n]);
If ($ t = 9 | $ t = 10 | (32 <= $ t & $ t <= 126 ))
            {
$ Tn = 1;
$ N ++;
$ Noc ++;
} Elseif (194 <=$ t & $ t <= 223)
            {
$ Tn = 2;
$ N + = 2;
$ Noc + = 2;
} Elseif (224 <=$ t & $ t <= 239)
            {
$ Tn = 3;
$ N + = 3;
$ Noc + = 2;
} Elseif (240 <=$ t & $ t <= 247)
            {
$ Tn = 4;
$ N + = 4;
$ Noc + = 2;
} Elseif (248 <=$ t & $ t <= 251)
            {
$ Tn = 5;
$ N + = 5;
$ Noc + = 2;
} Elseif ($ t = 252 | $ t = 253)
            {
$ Tn = 6;
$ N + = 6;
$ Noc + = 2;
} Else
            {
$ N ++;
            }

If ($ noc >=$ position)
            {
Break;
            }
        }
If ($ noc> $ position)
        {
$ N-= $ tn;
        }

$ Strcut = substr ($ string, 0, $ n );
$ Strcut = str_replace (array ($ pre. '&'. $ end, $ pre. '"'. $ end, $ pre. '<'. $ end, $ pre. '> '. $ end), array ('&', '"', '<', '>'), $ strcut );

$ Pos = strrpos ($ strcut, chr (1 ));
If ($ pos! = False)
        {
$ Strcut = substr ($ strcut, 0, $ pos );
        }
Return $ strcut. $ dot. $ append;
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.