Home > Article > Backend Development > Detailed explanation and usage of substr() function in php
Syntax:
string substr(string $string, int $start [, int $length]), which can be used in a longer string# Find matching strings or characters in ##, $string is the string to be processed, $start is the starting position to be selected, $length is the length to be selected.
$length is positive data from left Read characters from the right. When $length is a negative number, read characters from right to left. string Required, specifies that a part of the string should be returned. start Required , specifies where to start in the string.charlist Optional, specifies the length of the string to be returned, the default is until the end of the string.Positive number - specified in the string Position startNegative number - Start at the specified position from the end of the string0 - Start at the first character in the stringPHP example code is as follows:
$rest_1 = substr("abcdef", 2); // returns "cdef" $rest_2 = substr("abcdef", -2); // returns "ef" $rest1 = substr("abcdef", 0, 0); // returns "" $rest2 = substr("abcdef", 0, 2); // returns "ab" $rest3 = substr("abcdef", 0, -1); // returns "abcde" $rest4 = substr("abcdef", 2,0); // returns "" $rest5 = substr("abcdef", 2,2); // returns "cd" $rest6 = substr("abcdef", 2, -1); // returns "cde" $rest7 = substr("abcdef", -2,0); // returns "" $rest8 = substr("abcdef", -2,2); // returns "ef" $rest9 = substr("abcdef", -2,-1); // returns "e"PHP substr()
<?php echo mb_substr('我们都是好孩子hehe',0,9); ?>Output: We are allNow we add the
character setutf-8
<?php echo mb_substr('我们都是好孩子hehe',0,9,'utf-8'); ?>Output: We are all good kids he
The first one is to use three bytes as one Chinese character. This is the characteristic of utf-8 encoding. The description of the utf-8 character set is added below, so it is intercepted in units of one word.The following is the function in ecshop to intercept strings encoded in UTF-8
function sub_str($str, $length = 0, $append = true) { $str = trim($str); $strlength = strlen($str); if ($length == 0 || $length >= $strlength) { return $str; //截取长度等于0或大于等于本字符串的长度,返回字符串本身 } elseif ($length < 0) //如果截取长度为负数 { $length = $strlength + $length;//那么截取长度就等于字符串长度减去截取长度 if ($length < 0) { $length = $strlength;//如果截取长度的绝对值大于字符串本身长度,则截取长度取字符串本身的长度 } } if (function_exists('mb_substr')) { $newstr = mb_substr($str, 0, $length, EC_CHARSET); } elseif (function_exists('iconv_substr')) { $newstr = iconv_substr($str, 0, $length, EC_CHARSET); } else { //$newstr = trim_right(substr($str, 0, $length)); $newstr = substr($str, 0, $length); } if ($append && $str != $newstr) { $newstr .= '...'; } return $newstr; }
The above is the detailed content of Detailed explanation and usage of substr() function in php. For more information, please follow other related articles on the PHP Chinese website!