PHP String strtok() Function
The PHP String strtok() function is used to tokenize a string into smaller sections based on the specified delimiters. It accepts a String as input along with delimiters as a second argument.
Note: The first call to strtok makes use of the string argument. Every subsequent call to strtok needs simply the token, as it keeps track of its position in the current string.
To start fresh or tokenize a new string, simply use strtok() with the string input again. You can include several tokens in the token parameter. When a character from the token argument is found in the string, it is tokenized.
Syntax
Below is the syntax of the PHP String strtok() function −
string strtok ( string $string, string $token )
Alternative signature −
string strtok ( string $token )
Parameters
Here are the parameters of the strtok() function −
$string − (Required) It is the string to split.
$token − (Required) It is the delimiter used to divide up a string.
Return Value
The strtok() function returns a string token, or FALSE if no there is more tokens are available.
PHP Version
First introduced in core PHP 4, the strtok() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
Here is the basic example of the PHP String strtok() function to tokenize a string into smaller sections.
<?php
$input = "tutorials point simple easy learning.";
$token = strtok($input, " ");
while ($token !== false){
echo "$token\n";
$token = strtok(" ");
}
?>
Output
Here is the outcome of the following code −
tutorials point simple easy learning.
Example 2
Now this example uses the strtok() function to use multiple delimiters to split a string.
<?php
// Define a string here
$string = "apple;banana|cherry,grape";
$delimiters = ";|,";
// Get the first token
$token = strtok($string, $delimiters);
// Loop through each token
while ($token !== false) {
echo $token . "\n";
$token = strtok($delimiters);
}
?>
Output
This will generate the below output −
apple banana cherry grape
Example 3
In this example we will see how to restart tokenization by restarting strtok() function. So the program tokenizes two different strings by restarting strtok between them.
<?php
// Define strings here
$string1 = "one,two,three";
$string2 = "four|five|six";
// Tokenizing first string
$token = strtok($string1, ",");
while ($token !== false) {
echo $token . "\n";
$token = strtok(",");
}
echo "--- Restarting ---\n";
// Tokenizing second string
$token = strtok($string2, "|");
while ($token !== false) {
echo $token . "\n";
$token = strtok("|");
}
?>
Output
This will create the below output −
one two three --- Restarting --- four five six