PHP strtok Function Example | strtok() Function Tutorial
PHP strtok() is an inbuilt function that splits the string into smaller strings (tokens). The strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from the token. That is if you have the string like “It is the example string” you could tokenize this string into its words by using a space character as the token.
PHP String strtok() Function
The strtok() is an in-built function of PHP, which is similar to the C strtok() function. It is used to tokenize or split a string into small parts of string based on given delimiters.
It takes input string as an argument along with the delimiters (as a second argument).
It uses string argument only once when we invoke the strtok() for the first time.
After that, it needs other arguments as the split argument.
See the following syntax.
strtok(string, split)
A string parameter is required, and it defines the string.
The split parameter is required. Specifies one or more split characters. This parameter represents the splitting characters. It defines one or more delimiters or split characters by which string will get split. It is used when splitting up the string.
The strtok() returns a string token. It returns the strings separated by the given delimiters.
See the following code.
<?php // app.php $str = "Stranger Things is the best Netflix show"; $delimiter = "n"; $token = strtok($str, $delimiter); while($token !==false) { echo $token. "\n"; $token =strtok($delimiter); }
In the example above, note that it is only the first call to strtok() that uses a string argument.
After the first call, this function only needs a split argument, as it keeps the track of where it is in the current string.
If we want to tokenize the new string, call strtok() with the string argument again:
See the following output.
➜ pro php app.php Stra ger Thi gs is the best Netflix show ➜ pro
Also, note that you may put the multiple tokens in the token parameter. A string will be tokenized when any one of the characters in an argument is found.
If you have the memory-usage critical solution, you should keep in the mind, that strtok() function holds input string parameter (or reference to it?) in memory after usage.
Let’s see example 2.
<?php $str = "Millie Bobby Brown"; $delimiter = " "; $token = strtok($str, $delimiter); while($token !==false) { echo $token. "\n"; $token =strtok($delimiter); }
See the output.
➜ pro php app.php Millie Bobby Brown ➜ pro
Finally, PHP strtok Function Example | strtok() Function In PHP is over.