Whats the use of function strtok()
in PHP? How is better than other string function doing the same thing?
The strtok() function splits a string into smaller strings (tokens).
strtok() returns a NULL pointer. The token ends with the first character contained in the string pointed to by string2. If such a character is not found, the token ends at the terminating NULL character.
It is important to not that strtok does not allocate memory and create new strings for each of the tokens it finds. All the data still resides in the original string. Whenever strtok is called, it continues from where it left off and skips separators until it gets a valid character.
strtok is neither thread safe nor re-entrant because it uses a static buffer while parsing. This means that if a function calls strtok , no function that it calls while it is using strtok can also use strtok , and it cannot be called by any function that is itself using strtok .
There is no other string function that does the same thing. Functions like explode
return the complete split string in an array. strtok
on the other hand only returns one piece at a time, with each subsequent call returning the next piece. This is potentially much more economic and memory preserving for large strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With