Home > Article > Backend Development > Detailed introduction to PHP's commonly used string internal functions
This chapter describes several commonly used PHP Stringinternal functions. The PHP string internal functions we describe below are: echo, print, strlen, trim, ltrim , rtrim, substr, strtolower, strtoupper, str_replace.
echo and print
See the difference between PHP echo and PHP echo and print for details.
strlen
strlen function can get the length of a string. In the example below, the length of the resulting variable $a is 8.
$a = ' abcdef '; echo strlen($a); //8
trim
trim The function of the trim function is to remove the spaces on both sides of the string. For example, in the example below, the value of variable $a is 'abcdef', and there is a space on both sides of the string. After trim, since the two spaces on both sides of the string are removed, the length of the string is 6.
$a = ' abcdef '; echo strlen(trim($a)); //6
ltrim
ltrim function is to remove the spaces on the left side of the string.
echo 'nice',' try'; //nice try echo 'nice',ltrim(' try'); //nicetry
rtrim
rtrim The function of the rtrim function is to remove the spaces on the right side of the string.
echo 'a ', 'b'; //a b echo rtrim('a '),'b'; //ab
substr
A part of the string can be obtained through the substr function. The syntax of the substr function is as follows:
substr(string,start,length)
It means starting from the start position of the string string, intercept a string of length length. The first character of string string is at position 0, not 1. The example is as follows:
echo substr('blablar.com',0,3); //bla
The above example indicates that starting from the first character of the string, 3 characters are intercepted, and the return result is bla.
echo substr('blablar.com',3,5); //blar.
The above example means starting from the fourth character of the string blablar.com, intercepting 5 characters, and the result is blar.
You can also not write the parameter length, which means to intercept all subsequent strings from the start position, such as:
echo substr('blablar.com', 3); //blar.com
strtolower
strtolower The function is to turn all strings into lowercase. An example is as follows:
echo strtolower('BlaBlar.COM');//blablar.com
strtoupper
strtoupper and strtolower, on the contrary, function to make all strings uppercase. An example is as follows:
echo strtoupper('china'); //CHINA
str_replace
str_replace is used to replace strings. The syntax of the str_replace function is as follows:
str_replace(search,replace,subject)
It means that in the subject string, find any string that matches search, and then replace all search strings with replace.
The example is as follows:
echo str_replace("bla","CHA","blablar"); //CHACHAr
In the above example, CHA is used to replace all bla in the blablar string, and the returned result is CHACHAr.