Home > Backend Development > PHP Tutorial > Analysis of the advantages of strtok PHP strtok function

Analysis of the advantages of strtok PHP strtok function

WBOY
Release: 2016-07-29 08:42:00
Original
1272 people have browsed it

The advantages are:

1. Multiple separators can be defined at one time. When the function is executed, it cuts by a single delimiter instead of the entire delimiter, while explode cuts by the entire delimiter string. For this reason, explode can be cut in Chinese, but strtok cannot and will be garbled.

2. When using while or for with strtok() to traverse, you can change the separator at any time, or use break to terminate cutting at any time.

Example 1: Demonstrate using Chinese + explode to cut

$string = "This is the PHP Forum Forum Section Forum Column Forum H Administrator Forum Member";
$arr = explode("Forum",$string) ;
foreach($arr as $v)
{
echo $v."
";
}
echo "-------------
";

Return:

This is PHP
section
column
Hadmin
member
-------------

Example 2: Demonstrate changing the cutter. Note that there is no longer an "H" separator in WHILE. Instead just use spaces.

$string = "This is the PHP Forum Forum Section Forum Column 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; / /Can jump out at any time.
//$n++;
}
echo "-------------
";

Return:

This is P
P Forum
Forum Section
Forum Column
Forum H Administrator
Forum Member
-------------

Example 3: Demonstrate multiple delimiters.

$string = "This istan examplenstring";
$tok = strtok($string, " nt"); #Space, newline, TAB
while ($tok !== false) {
echo "$ tok
";
$tok = strtok(" nt");
}
echo "-------------
";

Return:

This
is
an
example
string
-------------

$string = "abcde 123c4 99sadb c99b5232" ;
$tok = strtok($string, "bc");
while ($tok !="") {
echo "$tok
";
$tok = strtok("bc");
}
echo "-------------
";

Return:

a
de 123
4 99sad
99
5232
-------------

Example 4: Demonstrates using for to traverse:

$line = "leontatkinsontleon@clearink.com";
for($ token = strtok($line,"t");$token!="";$token=strtok("t"))
{
print("token: $token
n");
}

Return:

token: leon
token: atkinson
token: leon@clearink.com

The above has introduced the analysis of the advantages of strtok PHP strtok function, including strtok content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template