The strtok Function
The strtok
function sequentially splits a string into tokens (parts) using specified delimiters. The first call to the function takes the string and delimiters, subsequent calls work with the same string until all tokens are returned. When tokens are exhausted, the function returns false
.
Syntax
strtok(string, token);
Example
Split a string by spaces:
<?php
$string = "Hello world! How are you?";
$token = strtok($string, " ");
while ($token !== false) {
echo $token . "\n";
$token = strtok(" ");
}
?>
Code execution result:
Hello
world!
How
are
you?
Example
Split a string by multiple delimiters:
<?php
$string = "one,two-three.four";
$token = strtok($string, ",-.");
while ($token !== false) {
echo $token . "\n";
$token = strtok(",-.");
}
?>
Code execution result:
one
two
three
four