首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP explode() 與 implode() 深度解析:分割、組合與進階陣列轉換技巧

     編輯:PHP 綜合知識

explode() 與 implode() 是 PHP 字串與陣列互轉的核心函數組合。本文系統整理參數細節、limit 行為差異、鍵值對解析模式,並對比兩者的對稱關係。

一、explode():字串分割為陣列

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
參數說明
$separator分隔符,不可為空字串(否則回傳 false)
$string待分割字串
$limit正數:最多回傳 N 元素,最後一元素含剩餘內容;負數:排除最後 N 個元素;0:視為 1

基本範例

<?php
$fruits = "Apple Banana Orange Lemon";
print_r(explode(' ', $fruits));
// Array([0]=>Apple,[1]=>Banana,[2]=>Orange,[3]=>Lemon)

/etc/passwd 解析
$data = "gonn:*:1000:1000::/home/gonn:/bin/bash";
['user','pass','uid','gid','gecos','home','shell'] = explode(':', $data);
echo $user; // gonn
?>

limit 參數行為對照

<?php
$str = 'one|two|three|four';
print_r(explode('|', $str, 2));   // [one, two|three|four]
print_r(explode('|', $str, -1));  // [one, two, three]  (排除最後 1)
print_r(explode('|', $str, -2));  // [one, two]        (排除最後 2)
?>

二、進階應用:字串轉鍵值陣列

支援 key=value 格式,自動修剪空白:

<?php
function stringToKeyedArray(string $str, string $delimiter = ',', string $kv = '=>'): array {
    $result = [];
    foreach (explode($delimiter, $str) as $segment) {
        $segment = trim($segment);
        if ($segment === '') continue;
        if (($pos = strpos($segment, $kv)) !== false) {
            $key = trim(substr($segment, 0, $pos));
            $val = trim(substr($segment, $pos + strlen($kv)));
            $result[$key] = $val;
        } else {
            $result[] = $segment; // 無鍵名則以數字索引
        }
    }
    return $result;
}

$input = 'a=>1, b=>2, c, d=>hello world';
print_r(stringToKeyedArray($input));
// [a=>1, b=>2, 0=>c, d=>hello world]
?>

三、implode():陣列組合為字串

implode(string $separator, array $array): string
// 歷史相容:implode(array $array): string(不推薦)

將陣列 value 以分隔符串聯,忽略鍵名:

<?php
$arr = ['Hello', 'World!', 'Beautiful', 'Day!'];
echo implode(' ', $arr); // Hello World! Beautiful Day!

// 實用場景:SQL IN 列表
$ids = [1,3,5,7];
$placeholders = implode(',', array_fill(0, count($ids), '?')); // ?,?,?,?
$sql = "SELECT * FROM users WHERE id IN ($placeholders)";
?>

四、兩者對稱性與效能提示

  • implode(explode($sep, $str), $sep) === $str 不一定成立(多重分隔符會合併)。
  • 大量字串拼接建議用 implode() 而非 . 運算子,減少記憶體重新分配。
  • explode() 在已知固定格式(如 CSV、日誌)時極快;複雜格式請改用 str_getcsv() 或正則。

五、常見陷阱

  1. 分隔符為空字串:拋出 ValueError(PHP 8.0+)或回傳 false。
  2. 多字元分隔符:explode('::', $str) 正常運作,但 preg_split() 更彈性。
  3. 編碼不一致:多位元組字串(UTF-8 中文)作為分隔符時,確保字串編碼一致。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved