Everyone knows that there are functions substr and substring for string interception in js. 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 of the string
Negative number - starts at the specified position from the end of the string
0 - Start 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 - returns from the position of the start parameter
Negative number - returns from the end of the string
Detailed explanation of the usage of PHP substr()
Definition and usage
substr() function returns a part of the string. Using the substr() function to intercept Chinese may cause garbled characters. It is recommended to use the mb_substr() function to intercept Chinese.
Syntax
substr(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 |
Optional. Specifies the length of the string to be returned. The default is until the end of the string.
|
Tips and Notes
Note: If start is a negative number and length is less than or equal to start, then length is 0.
Example
<?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 has introduced the correct usage of substr and substring in PHP and the introduction of related parameters, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.