Home > php教程 > PHP源码 > body text

php中explode与split函数的区别

WBOY
Release: 2016-06-08 17:23:22
Original
1010 people have browsed it

在一个层面来看php中的explode与split函数没什么区别都用来把字符以什么分开成数组了,但仔细看一下explode与split还是有区别的,下面我来给大家介绍一下。

<script>ec(2);</script>

首先来看下两个方法的定义:

函数原型:array split (string $pattern, string $string [, int $limit])

函数原型:array explode ( string $separator, string $string [, int $limit])

初看没有啥差别,貌似功能都一样。我就犯了这个错误。 请注意两个函数的第一个参数string $pattern和string separator,一个是$pattern说明是正则字符串,一个是$separator是普通字符串。 看下面的代码:

 代码如下 复制代码

$test = end(explode('.', 'abc.txt'));

echo $test;//output txt

换成:

$test1 = end(split('.','abc.txt'));

echo $test1;//no output

用split的正确做法是:加转义符号

$test1 = end(split('.','abc.txt'));

echo $test1;//output txt

 
分析:"." 符号是正则表达式的关键字所以split无效,而explode有效。


解析可能用斜线,点,或横线分割的日期:  

例子   2.   split()   例子

//   分隔符可以是斜线,点,或横线
$date   =   "04/30/1973 ";
list($month,   $day,   $year)   =   split   ( '[/.-] ',   $date);
echo   "Month:   $month;   Day:   $day;   Year:   $year
n ";
?>    


想仿效   Perl   中类似的   @chars   =   split( ' ',   $str)   行为,请参考   preg_split()   函数中的例子。  

注意   pattern   是一个正则表达式。如果想要用的分割字符是正则表达式中的特殊字符,要先将其转义。如果觉得   split()(或其它任何   regex   函数)行为古怪的话,请阅读包含在   PHP   发行包中   regex/   子目录下的   regex.7   文件。该文件是手册页面格式

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!