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
phpstrtok(string, token);
Example
Split a string by spaces:
php<?php
$string = "Hello world! How are you?";
$token = strtok($string, " ");
while ($token !== false) {
echo $token . "\n";
$token = strtok(" ");
}
?>
Code execution result:
phpHello
world!
How
are
you?
Example
Split a string by multiple delimiters:
php<?php
$string = "one,two-three.four";
$token = strtok($string, ",-.");
while ($token !== false) {
echo $token . "\n";
$token = strtok(",-.");
}
?>
Code execution result:
phpone
two
three
four