What is the strtok() method in PHP?
Overview
The strtok() method splits a string value at the points where an indicated delimiter is found in the string. Just like the explode() method, it splits a string into separate smaller chunks. But unlike the explode() method, it behaves differently, especially in handling its delimiter.
For example, a string
$A = "-man--knows". Now, strtok($A,"-") will produce "man", "-" and "knows" on successive calls, ignoring the "-" at the start of the string and the "-" where they appear side by side. The explode() method will produce an array, ["-","man","-","knows"].
When a string is tokenized using the strcoll() method, if we don’t iterate over process while strcoll() is still true, we’ll only get a single token even where there is multiple. Refer to the output on line 5 and line 13 in the code snippet below.
Syntax
The following is the syntax for strtok():
strcoll($token_source,$delimiter)
Parameters
$token_source: This is the string value from which tokens will be created.$delimiter: This is a string value, which will serve as the point at which the$token_sourcewill be split to form the tokens.
Return value
This function returns a string value if the tokens were created successfully. However, a boolean false will be returned if there is no token to create.
Example
<?php$token_source = "This word will be tokenized at spaces";//createing tokens off $token at "t"$token = strtok($token_source, "t"); //output=>This word would beecho($token) ."<br/>";//loop through $tok, to return token at each iterationwhile ($token !== false) {echo "The token in this iteration is -: $token <br/>";//split $token at whitespace points$token = strtok(" ");}//$token1 = strtok('/creating tokens', '/');$token2 = strtok('creating tokens');var_dump($token1, $token2);?>
Explanation
-
Line 2: We declare a variable
$token_sourcethat will serve as the string from which tokens will be created. -
Line 5: We use the
strtok()method to create tokens using"t"as the token separator. -
Lines 9–4: We start and end a
whileloop block. Inside of this loop, we print the value of using thestrtok()method on the variable$token_sourcesuccessive in order to get all the available tokens. -
Line 17: We use the
strtok()method on a string, which will return a token, while on line 18 using the same string, but omitting the delimiter it will returnfalse. -
Line 19: We use the
var_dumpmethod to display the output from lines 17 and 18.