strtok – PHP String Functions
Syntax :
Description :
It’s an inbuilt function of PHP. strtok() function Tokenize string or we can say splits a string into smaller strings (tokens).
if you have a string like “Hi from tutorialmines.” you could tokenize this string into its individual words by using the space character as the token.
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use.
Parameter :
[table caption=”” width=”100%” colwidth=”15%|15%|15%|55%” colalign=”left|left|left|left”]
Name, Required /Optional, Value Type, Description
string, Required, String, String to splitted into smaller substrings.
token, Required, String, delimiter by which string will be splitted.
[/table]
Output :
Return a string token.
Related articles : str_split(), explode() .
strtok() – PHP Functions Example 1 : only the first call to strtok() that uses the string argument. After the first call, this function only needs the split argument, as it keeps track of where it is in the current string. To tokenize a new string, call strtok() with the string argument again:
<?php $str = "Hi from tutorialmines."; $token = strtok($str, " "); while ($token !== false) { echo "$token\n"; $token = strtok(" "); } ?>
Output of above code in the browser is as below:
from
tutorialmines.
strtok() – PHP Functions Example 2 : How it behaves when empty part found
<?php $first_token = strtok('$tutorialmines', '$'); $second_token = strtok('$'); var_dump($first_token, $second_token); ?>
Output of above code in the browser is as below:
bool(false)