PHP strtok() Function

Usage — The PHP strtok() function is used to tokenize a string. In other words, it will split a string into smaller strings or tokens.

It has the following syntax:

PHP

string strtok ( string $str , string $token )
string strtok ( string $token )

Here is an example of using strtok():

PHP

$string = "Apple Mango Banana Grapes";
$token = strtok($string, " ");

// Output — Apple,Mango,Banana,Grapes,
while ($token !== false) {
    echo "$token,";
    $token = strtok(" ");
}

Return Value — This function returns a string token.

Additional Information — Please keep in mind that only the first call to strtok() uses the string argument. Every subsequent call to strtok() only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok() with the string argument again to initialize it.

You can also put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument is found.

PHP Version and Changelog — The strtok() function is available in PHP 4, PHP 5, PHP 7.

Relevant Functions — Other related PHP functions that you should know about are: split which splits a string into array by regular expression and explode() which splits a string by another string.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

str

The str parameter is used to specify the string being split up into smaller strings (tokens). This is a required parameter.

token

The token parameter is used to specify the delimiter(s) used when splitting up str. This is a required parameter.

Working Examples

Here are some examples of using the strtok() function:

PHP

$string = "Apple\Mango|Banana_Grapes";
$token = strtok($string, "\_|");

// Output — "Apple Mango Banana Grapes "
while ($token !== false) {
    echo "$token ";
    $token = strtok("\_|");
}

Further Reading

  1. You can read more about the PHP strtok() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top