Home >Backend Development >PHP Problem >How to disassemble a string by given symbols in PHP
In the previous article "PHP String Learning: Dividing Strings into Substrings of Smaller Lengths", we introduced the method of dividing strings according to character length. This time we introduce another method of splitting strings - splitting strings according to specified symbols (i.e. delimiters). Interested friends can learn about it~
First of all, we have such a character String:
$string = "Hello world Hello world";
If you want to split the string based on spaces, output:
Hello world Hello world
How to do this? Simple! Today I will introduce two methods to you.
First let’s take a look at the first method:
"; $token = strtok(" "); } ?>
Output result:
As can be seen, we use strtok($string, " ")
to split the string $string based on spaces and split the string into smaller substrings.
But because the strtok() function only takes out some fragments from the string at a time, you need to use the while() statement to call strtok() repeatedly.
And the strtok() function only needs to use the $string parameter when it is called for the first time. strtok() in the while loop only needs the $split parameter to specify the separator (can be different from the first time) ; Reason: The strtok() function maintains the position of its own internal pointer in the string. If you want to reset the pointer, you can re-pass the string to the strtok() function.
"; $token = strtok("l"); } ?>
Output result:
Okay, the first method is introduced. Let’s take a look at the second method:
Output result:
##As can be seen, we useexplode (" ",$string)Split the string $string based on spaces, split the string into smaller substrings, and then combine these substrings into an array and return it.
foreach($token as $value){ echo $value."<br>"; }Output result: Okay That’s it for now. If you want to know anything else, you can click here. → →Finally, I would like to recommend a free video tutorial on PHP arrays:
PHP function array array function video explanation, come and learn!
The above is the detailed content of How to disassemble a string by given symbols in PHP. For more information, please follow other related articles on the PHP Chinese website!