explode() 與 implode() 是 PHP 字串與陣列互轉的核心函數組合。本文系統整理參數細節、limit 行為差異、鍵值對解析模式,並對比兩者的對稱關係。
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
?>
<?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(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() 或正則。ValueError(PHP 8.0+)或回傳 false。explode('::', $str) 正常運作,但 preg_split() 更彈性。