PHP Function Reference

PHP strtok() Function



The PHP strtok() function splits a string str into smaller strings (tokens), with each token being delimited by any character from delim. Only the first call to strtok() uses the string argument. Every subsequent call to strtok() only needs delim to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string, simply call strtok() with the string argument again to initialize it.

Syntax

strtok(str, delim)

Parameters

str Required. Specify the string to split up into smaller strings (tokens).
delim Required. Specify delimiter used when splitting up string.

Return Value

Returns a string token, or false if no more tokens are available.

Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.

Example: strtok() example

The example below shows the usage of strtok() function.

<?php
$str = "To be, \tor not \nto be, that \tis the \nquestion.";

//using tab and newline as tokenizing characters
$delim = "\t\n";

//getting the first token
$token = strtok($str, $delim);

//searching for all tokens and displaying it
while($token !== false) {
  echo "$token\n";
  $token = strtok($delim);
}
?>

The output of the above code will be:

To be, 
or not 
to be, that 
is the 
question.

Example: difference between strtok() and explode()

The example below illustrates the difference between strtok() and explode() function.

<?php
$str = ";aaa;;bbb;";

$parts = [];
//getting the first token
$tok = strtok($str, ";");

//searching for all tokens
while ($tok !== false) {
    $parts[] = $tok;
    $tok = strtok(";");
}
echo json_encode($parts),"\n";

//using explode() function
$parts = explode(";", $str);

//displaying the result
echo json_encode($parts),"\n";
?>

The output of the above code will be:

["aaa","bbb"]
["","aaa","","bbb",""]

❮ PHP String Reference