Analysis of Extracting Substring from PHP String
- 2021-12-12 08:06:19
- OfStack
In this paper, an example is given to describe the operation of extracting substrings from PHP strings. Share it for your reference, as follows:
Problem
You want to extract part 1 of a string from a specific position in the string. For example, for a user name entered into a 1 form, you want to get the first 8 characters of that user name.
Solve
Use
substr()
Select substring
$substring = substr($string,$start,$length);
$username = substr($_GET['username'],0,8);
Discuss
1. If both $strart and $length are positive numbers,
substr()
Returns a string of $lenfth characters starting with $start. The first position of the character is 0.
echo substr('I Love PHP!',3,5);
ove P
If you ignore $length,
substr()
Returns a substring from $strart to the end of the original string.
Positive starting position, no length specified
echo substr('I Love PHP!',3);
ove PHP!
If $start is greater than the length of the string,
substr()
false will be returned
If $start plus $length exceeds the end of the string,
substr()
Returns all characters from $start to the end of the string
echo substr('I Love PHP!',3,9);
ove PHP!
If $start is negative,
substr()
The reciprocal from the end of the string determines where the substring begins
echo substr('I Love PHP!',-4);
PHP!
echo substr('I Love PHP!',-4 , 3);
PHP
If the value of $start is negative and exceeds the beginning of the string,
substr()
Will treat $start as 0
If $length is negative,
substr()
It will count down from the end of the string to determine where it ends
echo substr('I Love PHP!',3 , -1);
Love PHP
echo substr('I Love PHP!',-4 , -2);
PH
See also
substr()
Documents related to
For more readers interested in PHP related contents, please check the topics on this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Encyclopedia of Operation Skills of PHP Array (Array)", "Introduction to Basic Grammar of PHP", "Introduction to Database Operation of php+mysql" and "Summary of Operation Skills of Common Database of php"
I hope this article is helpful to everyone's PHP programming.