Often see a novice asked PHP there is no similar to the ASP's left function or right function, to intercept a string on the left-hand side or the beginning of the N-character function. Of course the answer is yes. The SUBSTR function in PHP can do it, except that PHP has two functions in one.
Now sorted out the use of the SUBSTR function, done a few examples to solve the confusion of new people, Master please drift.
Let's take a look at the syntax of the PHP substr function:
String substr (string string, int start, int [length])
Parameter string is the string to be manipulated
Parameter start is the starting position of the string you want to intercept, and if start is negative, it means that the length character is intercepted from the penultimate start
Optional parameter length for the string you want to intercept, if not specified when used, the default is taken to the end of the string. If length is a negative number, the position from start to right to the penultimate length character at the end is represented
This function may feel awkward at first, but if you understand the syntax of PHP substr function, then his function is better than left and right, Stadion in ASP. Let's take a look at his usage here:
1, from the 4th character to intercept the end of the string, similar to the left in asp:
<?php $str = "www.icoa.cn"; Echo substr ($STR, 4);?>
Output: icoa.cn
2, PHP substr function from the right to intercept 3 characters, similar to the right-hand of the ASP:
<?php $str = "www.icoa.cn"; Echo substr ($str, -3);?>
Output:. cn
3. The PHP substr function intercepts 3 characters starting from the 4th character:
<?php $str = "www.icoa.cn"; Echo substr ($str, 4,3);?>
Output: ico
4, sometimes we know the beginning and end of a string, the middle is indefinite length of characters, in addition to using the PHP substr function of the regular outside we can also use SUBSTR implementation (of course, to get the middle of the character method there are N, this is just an example of the application of substr):
This example removes the first 4 characters and the ending 3 characters and outputs the middle string:
<?php $str = "www.icoa.cn"; Echo substr ($str, 4,-3);?>
Output: Icoa
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.