PHP strtok () function instance application. Compared with explode (), the strtok () function can control the pace. Cut strings as needed. The advantage is: 1. Multiple separators can be defined at a time. When a function is executed, the strtok () function can control the pace compared to explode () by a single separator. Cut strings as needed. Its advantages are:
1. Multiple separators can be defined at a time. When a function is executed, it is cut by a single separator rather than the entire separator, while explode is cut by the entire separator string. Therefore, explode can be cut in Chinese, while strtok won't. it will be garbled.
2. when using while or for with strtok (), you can change the separator at any time or use break to exit and terminate the cut at any time.
Example 1: show how to use Chinese + explode to cut
$ String = "this is a PHP Forum forum topic forum H administrator forum member ";
$ Arr = explode ("Forum", $ string );
Foreach ($ arr as $ v)
{
Echo $ v ."
";
}
Echo "-------------
";
Return value:
This is PHP
Forum
Topic
H Administrator
Member
-------------
Example 2: replace the cut character. Note that the separator "H" is not contained in the WHILE character. It only uses spaces.
$ String = "this is a PHP Forum forum topic forum H administrator forum member ";
$ Tok = strtok ($ string, "H"); // Space + H
$ N = 1;
While ($ tok! = False ){
Echo "$ tok
";
$ Tok = strtok (""); // Space
// If ($ n> 2) break; // you can jump out at any time.
// $ N ++;
}
Echo "-------------
";
Return value:
This is P
P Forum
Forum
Forum topic
Forum H Administrator
Forum members
-------------
Example 3: multiple delimiters are displayed.
$ String = "This istan examplenstring ";
$ Tok = strtok ($ string, "nt"); # space, line feed, TAB
While ($ tok! = False ){
Echo "$ tok
";
$ Tok = strtok ("nt ");
}
Echo "-------------
";
Return value:
This
Is
An
Example
String
-------------
$ String = "abcde 123c4 99sadbc99b5232 ";
$ Tok = strtok ($ string, "bc ");
While ($ tok! = ""){
Echo "$ tok
";
$ Tok = strtok ("bc ");
}
Echo "-------------
";
Return value:
A
De 123
4 99sad
99
5232
-------------
Example 4: Use for traversal:
$ Line = "leontatkinsontleon@clearink.com ";
For ($ token = strtok ($ line, "t"); $ token! = ""; $ Token = strtok ("t "))
{
Print ("token: $ token
N ");
}
Return value:
Token: leon
Token: atkinson
Token: leon@clearink.com
For lift (), the strtok () function can control the pace. Cut strings as needed. The advantage is: 1. Multiple separators can be defined at a time. The function is executed by a single separator...