Home > Article > Backend Development > PHP: Introduction to the usage differences between substr and substring
Everyone knows that the string interception characters in js have functions substr and sub string, what about PHP? PHP does not have a directly available substring function, but it does have a substr function.
If you don’t believe it, you can test it yourself. A correct piece of code is given below.
<? $a="me"; echo(substr($a,,));//输出me ?> 下面又给出一段错误的代码 <? $a="me"; echo(subString($a,,)); ?>
substr() function returns a part of a string.
substr(string,start,length)
string: The string to be intercepted
start:
Positive number - starts at the specified position in the string
Negative number - starts at the specified position from the end of the string
0 - starts at the first character in the string
length:
Optional. Specifies the length of the string to be returned. The default is until the end of the string.
Positive number - Return from the position of the start parameter
Negative number - Return from the end of the string
Detailed explanation of the usage of PHP substr()
Definition and usage
## The #substr() function returns a portion of a string. Using the substr() function to intercept Chinese may cause garbled characters. It is recommended to use the mb_substr() function to intercept Chinese. Syntaxsubstr(string,start,length)Parameters | Description |
---|---|
##string | Required. Specifies a part of the string to be returned.|
start | Required. Specifies where in the string to begin.
|
length |
可选。规定要返回的字符串长度。默认是直到字符串的结尾。
|
提示和注释
注释:如果 start 是负数且 length 小于等于 start,则 length 为 0。
例子
<?php $str = 'hello world!'; echo substr($str, 4); // o world! 左起第4开始向右截取到末尾 echo substr($str, 4, 5); // o wor 左起第4开始向右取5位 echo substr($str, 4, -1); // o world 左起第4与右起第1之间的字符 echo substr($str, -8, 4); // o wo 右起第8开始向右截取4位 echo substr($str, -8,-2); // o worl 右起第8与右起第2之间的字符 ?>
The above is the detailed content of PHP: Introduction to the usage differences between substr and substring. For more information, please follow other related articles on the PHP Chinese website!