Home  >  Article  >  php教程  >  php字符串分割函数explode的实例代码

php字符串分割函数explode的实例代码

WBOY
WBOYOriginal
2016-06-06 20:06:25857browse

在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;
?>

Statement:
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