String Processing has a large number of character or string processing functions in php. Let's summarize the learning notes for PHP string processing today.
String Processing has a large number of character or string processing functions in php. Let's summarize the learning notes on PHP string processing today, this is not only a learning note, but also has great advantages in developing applications.
PHP strings
A string variable is used to include the value of a string.
In this tutorial, we will introduce several of the most common functions and operators used to operate strings in PHP. after creating a string, we can operate on it, you can use a string directly in a function or store it in a variable.
Below, the PHP script assigns the string "Hello World" to a string variable named $ txt. the instance code is as follows:
-
- $ Txt = "Hello World ";
- Echo $ txt;
- ?>
- // Output of the above code:
- // Hello World
Now, let's try to use different functions and operators to operate our strings.
Concatenation Operator)
In PHP, there is only one string operator, and the concatenation operator (.) used to connect two string values. to connect two variables, use the dot operator (.), the instance code is as follows:
-
- $ Txt1 = "Hello World ";
- $ Txt2 = "1234 ";
- Echo $ txt1. "". $ txt2;
- ?>
- // Output of the above code:
- // Hello World 1234
As you can see, we used the concatenation operator twice in the preceding example, because we need to insert the third string.
To separate the two variables, we insert a space between $ txt1 and $ txt2.
Use strlen () function
The strlen () function is used to calculate the length of a string.
Let's calculate the string "Hello world !" The instance code is as follows:
-
- Echo strlen ("Hello world! ");
- ?>
- // Output of the above code: 12
String length information is often used in loops or other functions, because it is important to determine when the string ends (for example, in a loop, we need to end the loop after the last character in the string ).
Use the strpos () function
The strpos () function is used to retrieve a string or a character in a string. if a match is found in the string, this function returns the first matched position. If no match is found, returns FALSE.
Let's try to see if the sub-string "world" can be found in the string. the instance code is as follows:
-
- Echo strpos ("Hello world! "," World ");
- ?>
- // The output of the above code is: 6
As you can see, in our string, the position of the string "world" is 6, and 6 instead of 7 is returned, because the first position in the string is 0, not 1.