array explode(string $separator, string $string, int $limit = PHP_INT_MAX)
$separator 為空字串 → 回傳 false。$limit > 0:最多回傳 $limit 個元素,最後一個包含剩餘字串。$limit < 0:回傳除了最後 abs($limit) 個元素外的所有元素。$limit = 0:視同 1。<?php
$str = 'aaa,bbb,ccc,ddd,explode,jjjj';
$arr = explode(',', $str);
print_r($arr);
/*
Array(
[0] => aaa
[1] => bbb
[2] => ccc
[3] => ddd
[4] => explode
[5] => jjjj
)
*/
?>
<?php
$file = 'www.111cn.net.gif';
$extArr = explode('.', $file);
$ext = end($extArr); // 取得最後一個元素
echo $ext; // gif
// 更健壯寫法 (pathinfo)
$ext = pathinfo($file, PATHINFO_EXTENSION); // 推薦
?>
利用 count() > 1 判斷字串中是否包含分隔符:
<?php
$raw = $_MODULE['tg1_tjly'] ?? ''; // 例如 "標題|內容" 或僅 "單純內容"
if ($raw) {
$parts = explode('|', $raw);
if (count($parts) > 1) {
// 含有分隔符
$title = $parts[0];
$content = $parts[1];
} else {
// 無分隔符,整個字串視為內容
$title = '推薦理由';
$content = $raw;
}
} else {
$title = '輸入推薦理由標題';
$content = '輸入推薦理由內容...';
}
?>
<?php
$arr = ['apple', 'banana', 'orange'];
$str = implode(' | ', $arr); // "apple | banana | orange"
$arr2 = explode(' | ', $str); // 還原陣列
?>
explode() 比 preg_split() 快得多。preg_split('/\s+/', $str)。str_contains()、str_starts_with()、str_ends_with() 可先快速判斷再分割。