PHP: explode - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

fprintf echo

Last updated: Sat, 27 Jan 2007

view this page in

# explode

(PHP 3, 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`.

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, но для explode() это недопустимо. `separator` всегда должен содержать разделитель, а `string` - исходную строку.

> Замечание: Аргумент `limit` был добавлен в PHP 4.0.1

Пример 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; // *
?>`

> Замечание: Эта функция безопасна для обработки данных в двоичной форме.

См. также описание функций preg_split(), spliti(), split() и implode().

add a note User Contributed Notes
explode
jason dot minett at custoREMOVEmscripts dot co dot uk
01-Mar-2007 08:09
`A quick gotcha that had me head scratching for a while....
If the delimiter occurs right at the end of the string there will be an extra array element (an empty string):
<?php
$str = "aaa^elephant^chocolate^albatross^";
$arr = explode ("^", $str);
echo ("Array length: ".count($arr));
?>
---------------------------------
Array length: 5`
Nicoxinchao
27-Feb-2007 11:59
`insensitive case explode function:
<?php
function iExplode($Delimiter, $String, $Limit = '')
{
$Explode = array();
$LastIni = 0;
$Count = 1;
if (is_numeric($Limit) == false)
$Limit = '';
while ( false !== ( $Ini = stripos($String, $Delimiter, $LastIni) ) && ($Count < $Limit || $Limit == ''))
{
$Explode[] = substr($String, $LastIni, $Ini-$LastIni);
$LastIni = $Ini+strlen($Delimiter);
$Count++;
}
$Explode[] = substr($String, $LastIni);
return $Explode;
}
?>`
Alex
16-Jan-2007 02:03
`I was using explode("\n", $string) to split a huge string (~ 0,5 MB). This took about 15 minutes to complete!
Using strtok($string, "\n") (followed by several thousand strtok("\n") of course), the same splitting is done in less than a minute.`
orlandu96 at gmail dot com
16-Dec-2006 09:28
`A 'between' function that we've all been waiting for. I am not savvy with regex so I resorted to explode();
<?php
function between($beg, $end, $str) {
$a = explode($beg, $str, 2);
$b = explode($end, $a[1]);
return $beg . $b[0] . $end;
}
echo between('<a>', '</a>', 'fsdfsdfsd<a>fsdfsd<a><a></a>sdfsdfsdf')
//<a>fsdfsd<a><a></a>
?>`
seventoes at gmail dot com
09-Dec-2006 07: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));
?>`
Elad Elrom
20-Oct-2006 11:50
`// simple function to remove words if more than max allowed words or add a charcter once less than min
// 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;
}`
webmaster at saund-web dot com
13-Mar-2006 10:20
`If you want to split a price (float) into pounds and pence.
or dollors and cents etc etc.
$price = "6.20";
$split = explode(".", $price);
$pound = $split[0]; // piece1
$pence = $split[1]; // piece2
echo "&pound $pound . $pence\n";`
djogo_curl at yahoo
01-Dec-2004 04: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.`
ian at illumen dot co dot uk
24-Aug-2004 01:30
`If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.
<?php
$str = '';
$foo = explode( ":", $str );
print_r( $foo );
$foo = split( ":", $str );
print_r( $foo );
$foo = preg_split( "/:/", $str );
print_r( $foo );
?>
In all three cases prints
Array
(
� � [0] =>
)
This of course means that you must explicitly check to see if the value of the first element is blank, or must check to see if the string being split is blank.`
coroa at cosmo-genics dot com
16-Nov-2003 08: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");`
add a note
fprintf echo

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST