PHP substr () function

Source: Internet
Author: User

PHP substr () function can split the text, but to split the text if the inclusion of Chinese characters tend to encounter problems, you can use MB_SUBSTR ()/mb_strcut This function, Mb_substr ()/mb_strcut usage and substr () similar, Just in Mb_substr ()/mb_strcut to add more than one parameter to set the encoding of the string, but the general server does not open Php_mbstring.dll, you need to open the Php_mbstring.dll in php.ini.

123 <?phpechomb_substr(‘我们都是好孩子hehe‘,0,9);?>

Output: We all

Now we add the character set Utf-8

<?phpechomb_substr(‘我们都是好孩子hehe‘,0,9,‘utf-8‘);?>


Output: We're all good kids he

The first one is in three bytes for a Chinese, this is the characteristics of utf-8 encoding, followed by the Utf-8 character set description, so, is in a word to intercept the

The following is a function that intercepts UTF-8 encoded strings within Ecshop

1 function sub_str ($str, $length = 0, $append = True)
2 {
3 $str = Trim ($STR);
4 $strlength = strlen ($STR);
5
6 if ($length = = 0 | | $length >= $strlength)
7 {
8 return $STR; Intercept length equal to 0 or greater than or equal to the length of this string, return the string itself
9}
ElseIf ($length < 0)//If intercept length is negative
11 {
$length = $strlength + $length;//Then The intercept length is equal to the length of the string minus the intercept length
if ($length < 0)
14 {
$length = $strlength;//If the absolute value of the intercept length is greater than the length of the string itself, the length of the string itself is truncated
16}
17}
18
if (function_exists (' mb_substr '))
20 {
$newstr = mb_substr ($str, 0, $length, ec_charset);
22}
ElseIf (function_exists (' iconv_substr '))
24 {
$newstr = iconv_substr ($str, 0, $length, ec_charset);
26}
Else
28 {
//$newstr = Trim_right (substr ($str, 0, $length));
$newstr = substr ($str, 0, $length);
31}
32
if ($append && $str! = $newstr)
34 {
$newstr. = ' ... ';
36}
37
$newstr to return;
39}

PHP substr () function

Related Article

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.