Php custom function intercepts Chinese characters

Source: Internet
Author: User
There are many ways to intercept the length of Chinese characters in php. In this example, the user-defined function is used to meet this requirement. if you are interested, refer The code is as follows:
Function msubstr ($ str, $ start, $ len ){
$ Strlen = $ start + $ len;
For ($ I = 0; $ I <$ strlen; $ I ++ ){
If (ord (substr ($ str, $ I, 1)> 0xa0 ){
$ Tmpstr. = substr ($ str, $ I, 2 );
$ I ++;
} Else
$ Tmpstr. = substr ($ str, $ I, 1 );
}
Return $ tmpstr;

}

The code is as follows:
$ Str = "this character is long, ^ _ ^ ";
$ Short_Str = showShort ($ str, 4); // extract the first four Chinese characters and the result is: this character...
Echo "$ Short_Str ";
Function csubstr ($ str, $ start, $ len)
{
$ Strlen = strlen ($ str );
$ Clen = 0;
For ($ I = 0; $ I <$ strlen; $ I ++, $ clen ++)
{
If ($ clen >=$ start + $ len)
Break;
If (ord (substr ($ str, $ I, 1)> 0xa0)
{
If ($ clen> = $ start)
$ Tmpstr. = substr ($ str, $ I, 2 );
$ I ++;
}
Else
{
If ($ clen> = $ start)
$ Tmpstr. = substr ($ str, $ I, 1 );
}
}

Return $ tmpstr;
}
Function showShort ($ str, $ len)
{
$ Tempstr = csubstr ($ str, 0, $ len );
If ($ str <> $ tempstr)
$ Tempstr. = "..."; // you can modify the description here.

Return $ tempstr;
}

Let's take a look at the nagging method. is it concise?
The code is as follows:
$ Len = 19;
$ Text = "how to display only the first few words in a long news title, which is replaced? ";
Echo strlen ($ text) <= $ len? $ Text: (substr ($ text, 0, $ len). chr (0 )."....");

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.