when the encoding of $string is 'GBK' and $delimiter is '|' , the return value may be wrong.
for example:
<?php
$result = explode("|", "滕华弢|海青");
var_dump($result);
?>
and the result will be:
array (
0 => '滕华,
1 => '',
2 => '海青',
)
bcz "弢" 's GBK is '0x8f7c'. and "|" 's ASCII is '0x7c'.
So, all GBK-encoding characters include '7c' will lead to the error result.
explode
(PHP 4, PHP 5)
explode — 使用一个字符串分割另一个字符串
说明
array explode
( string $separator
, string $string
[, int $limit
] )
此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 separator 作为边界点分割出来。如果设置了 limit 参数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。
如果 separator 为空字符串(""),explode() 将返回 FALSE。如果 separator 所包含的值在 string 中找不到,那么 explode() 将返回包含 string 单个元素的数组。
如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。此特性是 PHP 5.1.0 中新增的。
由于历史原因,虽然 implode() 可以接收两种参数顺序,但是 explode() 不行。你必须保证 separator 参数在 string 参数之前才行。
Note: 参数 limit 是在 PHP 4.0.1 中加入的。
Example#1 explode() 例子
<?php
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>
Example#2 limit 参数例子
<?php
$str = 'one|two|three|four';
// 正数的 limit
print_r(explode('|', $str, 2));
// 负数的 limit(自 PHP 5.1 起)
print_r(explode('|', $str, -1));
?>
上例将输出:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Note: 本函数可安全用于二进制对象。
explode
gxd305 at gmail dot com
17-Nov-2009 09:47
17-Nov-2009 09:47
nick dot brown at free dot fr
15-Oct-2009 06:47
15-Oct-2009 06:47
My application was running out of memory (my hosting company limits PHP to 32MB). I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas. Total size of the biggest string, with 20000 triplets, is about 1MB.
The application needs to split the string into triplets, then split the triplet into numbers. In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array. The intermediate array of strings shouldn't be much bigger than the long string itself (1MB). And I expect some overhead from PHP, say 300% to allow for indexes etc.
Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character). I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it. Amazing.
The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string). Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string. Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory.
Moral: be careful when using explode() on big strings, as it can also explode your memory usage.
Jrg Wagner
13-Oct-2009 05:28
13-Oct-2009 05:28
Here is a very concise example for a quote aware explode - substrings in quotes (or another definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a built-in way to do this!
<?php
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
$resArr = array();
$n = 0;
$expEncArr = explode($enclose, $str);
foreach($expEncArr as $EncItem){
if($n++%2){
array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
}else{
$expDelArr = explode($delim, $EncItem);
array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
$resArr = array_merge($resArr, $expDelArr);
}
}
return $resArr;
}
?>
Anonymous
29-Sep-2009 06:20
29-Sep-2009 06:20
Note to the previous example: we can do the whole string->array conversion using explode() exclusively.
<?php
// converts pure string into a trimmed keyed array
function string_2_array( $string, $delimiter = ',', $kv = '=>')
{
if ($element = explode( $delimiter, $string ))
{
// create parts
foreach ( $element as $key_value )
{
// key -> value pair or single value
$atom = explode( $kv, $key_value );
if( trim($atom[1]) )
{
$key_arr[trim($atom[0])] = trim($atom[1]);
}
else
{
$key_arr[] = trim($atom[0]);
}
}
}
else
{
$key_arr = false;
}
return $key_arr;
}
?>
Anonymous
03-Sep-2009 10:18
03-Sep-2009 10:18
<?php
// converts pure string into a trimmed keyed array
function string2KeyedArray($string, $delimiter = ',', $kv = '=>') {
if ($a = explode($delimiter, $string)) { // create parts
foreach ($a as $s) { // each part
if ($s) {
if ($pos = strpos($s, $kv)) { // key/value delimiter
$ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
} else { // key delimiter not found
$ka[] = trim($s);
}
}
}
return $ka;
}
} // string2KeyedArray
$string = 'a=>1, b=>23 , $a, c=> 45% , true,d => ab c ';
print_r(string2KeyedArray($string));
?>
Array
(
[a] => 1
[b] => 23
[0] => $a
[c] => 45%
[1] => true
[d] => ab c
)
Anonymous
11-Aug-2009 01:55
11-Aug-2009 01:55
If you are exploding string literals in your code that have a dollar sign ($) in it, be sure to use single-quotes instead of double-quotes, since php will not spare any chance to interpret the variable-friendly characters after the dollar signs as variables, leading to unintended consequences, the most typical being missing characters.
<?php
$doubleAr = explode(" ", "The $quick brown fox");
$singleAr = explode(" ", 'The $quick brown fox');
echo $doubleAr[1]; // prints "";
echo $singleAr[1]; // prints "$quick";
?>
vzverev at nm dot ru
24-Jul-2009 10:33
24-Jul-2009 10:33
If you are going to use foreach after explode(), call reset() before foreach:
<?php
$arr = explode("\n", 'test \n test2 \n test3');
reset($arr);
foreach($arr as $line)
{ /* do something */ ; }
?>
marcus at synchromedia dot co dot uk
15-Jun-2009 09:50
15-Jun-2009 09:50
Just in case the comment about empty strings is not clear:
<?php
$a = array();
var_dump($a);
$s = implode("\n", $a);
var_dump($s);
$b = explode("\n", $s);
var_dump($b);
$b = preg_split('/\n/', $s,-1,PREG_SPLIT_NO_EMPTY);
var_dump($b);
?>
Results in:
array(0) {
}
string(0) ""
array(1) {
[0]=>
string(0) ""
}
array(0) {
}
i.e. exploding an empty string results in an array with one element. You can use preg_split to skip the empty item, but that may not be quite what you need should your array have empty elements intentionally.
SR
21-Apr-2009 10:50
21-Apr-2009 10:50
Keep in mind that explode() can return empty elements if the delimiter is immediately repeated twice (or more), as shown by the following example:
<?php
$foo = 'uno dos tres'; // two spaces between "dos" and "tres"
print_r(explode(' ', $foo));
?>
Array
(
[0] => uno
[1] => dos
[2] =>
[3] => tres
)
Needless to say this is definitely not intuitive and must be handled carefully.
Michael
19-Apr-2009 05:29
19-Apr-2009 05:29
Here's a simple script which uses explode() to check to see if an IP address is in an array (can be used as a ban-check, without needing to resort to database storage and queries).
<?php
function denied($one) {
$denied = array(
0 => '^255.255.255.255',
1 => '^255.250',
2 => '^255.255.250'
);
for ($i = 0 ; $i < sizeof($denied) ; $i++) {
if (sizeof(explode($denied[$i], '^' . $one . '$')) == 2) {
return true;
}
}
return false;
}
if (denied($_SERVER['REMOTE_ADDR'])) {
header('Location: denied.php');
}
?>
Navi
31-Mar-2009 08:03
31-Mar-2009 08:03
<?php
function my_explode($delim, $str, $lim = 1)
{
if ($lim > -2) return explode($delim, $str, abs($lim));
$lim = -$lim;
$out = explode($delim, $str);
if ($lim >= count($out)) return $out;
$out = array_chunk($out, count($out) - $lim + 1);
return array_merge(array(implode($delim, $out[0])), $out[1]);
}
?>
This function can assume `limit' parameter less than 0, for example:
<?php
print_r(my_explode('.', 'file.some.ext.jpg', -2));
?>
prints
Array
(
[0] => file.some.ext
[1] => jpg
)
adrian at bilsoftware dot com
24-Feb-2009 06:40
24-Feb-2009 06:40
<?php
function explode_escaped($delimiter, $string){
$exploded = explode($delimiter, $string);
$fixed = array();
for($k = 0, $l = count($exploded); $k < $l; ++$k){
if($exploded[$k][strlen($exploded[$k]) - 1] == '\\') {
if($k + 1 >= $l) {
$fixed[] = trim($exploded[$k]);
break;
}
$exploded[$k][strlen($exploded[$k]) - 1] = $delimiter;
$exploded[$k] .= $exploded[$k + 1];
array_splice($exploded, $k + 1, 1);
--$l;
--$k;
} else $fixed[] = trim($exploded[$k]);
}
return $fixed;
}
?>
Here's a function which explodes string with delimiter, but if delimiter is "escaped" by backslash, function won't split in that point. Example:
<?php
$result = explode_escaped(',', 'string, piece, group\, item\, item2, next\,asd');
print_r($result);
?>
Will give:
Array
(
[0] => string
[1] => piece
[2] => group, item, item2
[3] => next,asd
)
Elad Elrom
05-Dec-2008 01:02
05-Dec-2008 01:02
<?php
// Remove words if more than max allowed character are insert or add a string in case less than min are displayed
// Example: LimitText("The red dog ran out of thefence",15,20,"<br>");
function LimitText($Text,$Min,$Max,$MinAddChar) {
if (strlen($Text) < $Min) {
$Limit = $Min-strlen($Text);
$Text .= $MinAddChar;
}
elseif (strlen($Text) >= $Max) {
$words = explode(" ", $Text);
$check=1;
while (strlen($Text) >= $Max) {
$c=count($words)-$check;
$Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
$check++;
}
}
return $Text;
}
?>
Nobody
17-Nov-2008 09:38
17-Nov-2008 09:38
A really better and shorter way to get extension is via:
<?php $extension = end(explode('.', $filename)); ?>
this will print the last part after the last dot :)
shaun
30-Aug-2008 03:24
30-Aug-2008 03:24
For anyone trying to get an array of key => value pairs from a query string, use parse_str. (Better alternative than the explode_assoc function listed way down the page unless you need different separators.)
pinkgothic at gmail dot com
15-Oct-2007 05:26
15-Oct-2007 05:26
coroa at cosmo-genics dot com mentioned using preg_split() instead of explode() when you have multiple delimiters in your text and don't want your result array cluttered with empty elements. While that certainly works, it means you need to know your way around regular expressions... and, as it turns out, it is slower than its alternative. Specifically, you can cut execution time roughly in half if you use array_filter(explode(...)) instead.
Benchmarks (using 'too many spaces'):
Looped 100000 times:
preg_split: 1.61789011955 seconds
filter-explode: 0.916578054428 seconds
Looped 10000 times:
preg_split: 0.162719011307 seconds
filter-explode: 0.0918920040131 seconds
(The relation is, evidently, pretty linear.)
Note: Adding array_values() to the filter-explode combination, to avoid having those oft-feared 'holes' in your array, doesn't remove the benefit, either. (For scale - the '9' becomes a '11' in the benchmarks above.)
Also note: I haven't tested anything other than the example with spaces - since djogo_curl at yahoo's note seems to imply that explode() might get slow with longer delimiters, I expect this would be the case here, too.
I hope this helps someone. :)
seventoes at gmail dot com
10-Dec-2006 11:49
10-Dec-2006 11:49
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.
<?php
$string = "Something--next--something else--next--one more";
print_r(explode('--next--',$string));
?>
djogo_curl at yahoo
01-Dec-2004 08:50
01-Dec-2004 08:50
Being a beginner in php but not so in Perl, I was used to split() instead of explode(). But as split() works with regexps it turned out to be much slower than explode(), when working with single characters.
coroa at cosmo-genics dot com
17-Nov-2003 12:01
17-Nov-2003 12:01
To split a string containing multiple seperators between elements rather use preg_split than explode:
preg_split ("/\s+/", "Here are to many spaces in between");
which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");
