PHP strtok function

 The PHP strtok function is used to cut a string into smaller strings. For example, if a string is as long as "Good morning John.", through the PHP strtok function, set the cutting character to a space, and it can be cut into " "Good", "morning" and "John." The functions are similar to split , preg_split , explode ... and other functions. However, strtok has a characteristic that when processing the same string, it only needs to call the string for the first time, and there is no need to call the string for each subsequent cutting, unless a new string is to be processed.


Basic syntax of PHP strtok function

strtok( $string, $token)


There are two parameters in the parentheses of the strtok function. The first parameter $string is the string to be cut, a required item, and the second parameter $token is the cut character. What is more special is that the cut character can be used once After setting several different characters, the strtok function can judge the different characters, as long as it encounters a cutting character, it will separate the string.

PHP strtok function example
<?php
$new_string = "Welcome to Wibibi.\nHave a good day.";
$tok_str = strtok ($new_string, "\n");
while ($tok_str !== false) {
 echo "$tok_str<br / >";
 $tok_str = strtok (" \n");
}
?>
The output of the above example is
Welcome
to
Wibibi.
Have
a
good
day.
In the example, the strtok function is used for the first time, and two parameters are used, $new_string and cutting characters. There are two cutting characters here, namely the space and the symbol of \n, and then we use PHP while loop to cut each The part that comes out is echo displayed on the webpage respectively. When the strtok function is used for the second time, there is no more call to $new_string! You only need to use the cutting characters to cut the string, because the PHP strtok function will automatically remember the last cutting position.

Post a Comment

0 Comments