略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: explode

2024-12-23

explode

(PHP 4, PHP 5, PHP 7, PHP 8)

explode使用一个字符串分割另一个字符串

说明

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 separator 作为边界点分割出来。

参数

separator

边界上的分隔字符。

string

输入的字符串。

limit

如果设置了 limit 参数并且是正数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。

如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。

如果 limit 是 0,则会被当做 1。

注意:

在 PHP 8.0 之前,implode() 可以接收两种参数顺序。 但请注意,explode() 从未支持乱序传入参数:你必须保证 separator 参数在 string 参数之前。

返回值

此函数返回由字符串组成的 array,每个元素都是 string 的一个子串,它们被字符串 separator 作为边界点分割出来。

如果 separator 为空字符串(""),explode() 将抛出 ValueError。 如果 separator 所包含的值在 string 中找不到,并且使用了负数的 limit , 那么会返回空的 array, 否则返回包含 string 单个元素的数组。 如果 separator 值出现在了 string 参数的开头或末尾, 将在返回 array 相应的头部或尾部添加 array 空值。

更新日志

版本 说明
8.0.0 现在开始,当 separator 参数传入空字符串时(""), explode() 会抛出 ValueError。 在早期版本中,explode() 会返回 false

范例

示例 #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// *

?>

示例 #2 explode() return examples

<?php
/*
  字符串内不包含分隔字符时,
  会简单返回只有一个原始字符串元素的 array。
*/
$input1 "hello";
$input2 "hello,there";
$input3 ',';
var_dumpexplode','$input1 ) );
var_dumpexplode','$input2 ) );
var_dumpexplode','$input3 ) );

?>

以上例程会输出:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

示例 #3 limit 参数的例子

<?php
$str 
'one|two|three|four';

// 正数的 limit
print_r(explode('|'$str2));

// 负数的 limit
print_r(explode('|'$str, -1));
?>

以上例程会输出:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

注释

注意: 此函数可安全用于二进制对象。

参见

add a noteadd a note

User Contributed Notes 7 notes

up
7
Gerben
3 months ago
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.

For example, maybe you are splitting part of a URI by forward slashes (like "articles/42/show" => ["articles", "42", "show"]). And maybe you expect that an empty URI will result in an empty array ("" => []). Instead, it will contain one element, with an empty string:

<?php

$uri
= '';
$parts = explode('/', $uri));
var_dump($parts);

?>

Will output:

array(1) {
  [0]=>
  string(0) ""
}

And not:

array(0) {
}
up
11
bocoroth
1 year ago
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string "1"!

var_dump(explode(',', null)); //array(1) { [0]=> string(0) "" }
var_dump(explode(',', false)); //array(1) { [0]=> string(0) "" }

var_dump(explode(',', true)); //array(1) { [0]=> string(1) "1" }
up
0
henrik Schmidt
1 year ago
"Return value" text needs updating for php 8, an empty delimiter now throws an Exception.
up
-7
Emilio Bravo
1 year ago
$string = "PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION";
$exploded = explode("::",$string);
/*

explode('::',$string) = eliminate every :: and for each division of ::make an array element

Example:

PDO::ERRMODE_EXCEPTION (exploded) = array     (
                                                    [0] => string PDO
                                                    [1] => string ERRMODE_EXCEPTION
                                               )
Example:

$exploded[0] = "PDO";
*/
foreach ($exploded as $index) {
    echo $index . "\n";
}
/*

Output:

PDO
ATTR_ERRMODE => PDO
ERRMODE_EXCEPTION

*/
up
-7
joshuachidiebere17217 at gmail dot com
4 months ago
<?php
/*Array to split*/
$task =["Teach","Assess","Record ","Examine","Investigate"];
/*use Implode() function to convert
$task into arrays of string
*/
$string=implode(",", $task);
/*use explode() function to seperate $string into different
$task into arrays of string
*/ 
explode(",", $string);
foreach (
$task as $variable => $tk) {
$variable>0;
$variable++;
echo
'$variable_'.$variable.' is ' .$tk.'<br>';
}
echo
min(3,6);
?>
up
-18
David Spector
1 year ago
When using 'explode' to create an array of strings from a user-specified string that contains newline characters, you may wish the resulting array to correctly reflect the user's intentions by ignoring any final empty line (many users like to end multi-line input with a final newline, for clarity).

Here is a function to call after 'explode' to support this effect:

// When using explode, delete the last line in the array of lines when it is empty
function IgnoreEmptyLastLine(&$linesArr)
    {
    $last=count($linesArr)-1;
    if ($last>=0 && !$linesArr[$last])
        unset($linesArr[$last]);
    } // IgnoreEmptyLastLine
up
-56
leandro at primersistemas dot com dot br
1 year ago
function aexplode($delimiters,$string,$trimduplicate = false) {
    if (!is_array($delimiters))
        return explode($delimiters,$string);
    $stringaux = str_replace($delimiters, $delimiters[0], $string);
    if ($trimduplicate)
        while (strpos($stringaux,$delimiters[0].$delimiters[0]) !== false)
            $stringaux = str_replace($delimiters[0].$delimiters[0],$delimiters[0],$stringaux);
    return explode($delimiters[0],$stringaux);
}

This functions will work and accept array.

官方地址:https://www.php.net/manual/en/function.explode.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3