Its advantages are:
1, you can define multiple separators at once. When a function is executed, it is cut by a single delimiter rather than by the entire separator, while the explode is cut by the entire separator string. Therefore, explode can be cut in Chinese, and strtok is not, will be garbled.
2, in the use while or for with strtok () traversal, you can change the separator at any time, you can break out at any time to stop cutting.
Example 1: Demo to cut with Chinese +explode
$string = "This is the PHP Forum Forum Forums Forum Column Forum H Administrator Forum members"; $arr = explode ("forum", $string); foreach ($arr as $v) { echo $v. " <br/> "; } echo "-------------<br/>"; |
Return:
This is PHP
Section Column H Admin Member -------------
|
Example 2: Demonstrates a replacement cutter, noting that the "H" separator is no longer in the later while. And just use a space.
$string = "This is the PHP Forum Forum Forums Forum Column Forum H Administrator Forum members"; $tok = Strtok ($string, "H"); Space +h $n = 1; while ($tok!== false) { echo "$tok <br/>"; $tok = Strtok (""); Space if ($n >2) break; Can jump at any time. $n + +; } echo "-------------<br/>"; |
Return:
This is P P Forum Forum section Forum columns Forum h Admin Forum members ------------- |
Example 3: Demonstrates multiple separators.
$string = "This Is\tan example\nstring"; $tok = Strtok ($string, "\n\t"); #空格, linefeed, TAB while ($tok!== false) { echo "$tok <br/>"; $tok = Strtok ("\n\t"); } echo "-------------<br/>"; |
Return:
This Is An Example String ------------- |
$string = "ABCDE 123c4 99sadbc99b5232"; $tok = Strtok ($string, "BC"); while ($tok!= "") { echo "$tok <br/>"; $tok = strtok ("BC"); } echo "-------------<br/>"; |
Return:
A De 123 4 99sad 99 5232 ------------- |
Example 4: Demonstrates traversing with for:
$line = "leon\tatkinson\tleon@clearink.com"; for ($token = Strtok ($line, "\ t"); $token!= ""; $token =strtok ("\ t") { Print ("token: $token <br>\n"); } |
Return:
Token:leon Token:atkinson Token:leon@clearink.com
|