在php中分割一个字符串,我们可以使用函数explode(),其原型如下
array explode (string $separator, string $string [, int $limit])
该函数有3个参数,第一个参数$separator设置一个分割字符(串)。第二个参数$string指定所要操作的字符串。$limit参数是可选的,指定最多将字符串分割为多少个子串。
该函数返回一个由被分割的子串组成的数组。
来看下面的例子,对一个由逗号分隔的多行文本数据进行分析。
例1,分割字符串。
代码如下:
$this_year = 2013;
$text = <<< EOT
祝无双,F,1982,广东,普遍职员
李三兵,M,1981,河北,普通职员
赵朴秀,F,1980,韩国,项目经理
EOT;
$lines = explode("\n", $text); //将多行数据分开
foreach ($lines as $userinfo) {
$info = explode(",", $userinfo, 3); //仅分割前三个数据
$name = $info[0];
$sex = ($info[1] == "F")? "女" : "男";
$age = $this_year - $info[2];
echo "姓名: $name $sex . 年龄:$age
";
}
/* 输出结果是:
姓名:祝无双 女 年龄:31
姓名:李三兵 男 年龄:32
姓名:赵朴秀 女 年龄:33
*/
?>
以上代码,先对文本按行进行分割,然后将每行字符串按","进行分割,并取前三个数据进行处理分析,然后进行整理并输出。
另外,为大家介绍php的另一个内建函数implode(),用于连接数组成为字符串。
与分割字符串函数相对应的是implode()函数,它的别名函数叫做join(),函数原型分别如下。
string implode(string $glue, array $pieces)
string join(string $glue, array $pieces)
implode()或join()函数可以将数组$pieces中的元素用指定的字符$glue连接起来。
下面为大家举一个简单的例子,供学习参考。
例2:
代码如下:
$fruits = array('apple', 'banana', 'pear');
$str = implode(", ", $fruits);
echo $str;
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software