The difference between explode and split in php

  • 2020-05-26 07:53:07
  • OfStack

First, let's look at the definitions of the two methods:

Function prototype: array split (string $pattern, string $string [, int $limit])

Function prototype: array explode (string $separator, string $string [, int $limit])

At first glance there is no difference, it looks like the function is the same. I made that mistake. Note that the first arguments of the two functions string $pattern and string separator, 1 for $pattern, and 1 for $separator, are regular strings, and 1 for $separator, normal strings.

Look at the following code:
 
$test = end(explode('.', 'abc.txt')); 
echo $test;//output txt 

Replaced by:
 
$test1 = end(split('.','abc.txt')); 
echo $test1;//no output 

The correct way to use split is to add an escape symbol
 
$test1 = end(split('\.','abc.txt')); 
echo $test1;//output txt 


Analysis: the "." symbol is the keyword of the regular expression, so split is invalid, while explode is valid.

Related articles: