explode()
是 PHP 中一個非常有用的字符串處理函數,它可以將一個字符串按照指定的分隔符拆分成一個數組。以下是一些實用的案例:
$csv = "apple,banana,orange";
$array = explode(",", $csv);
print_r($array); // 輸出: Array ( [0] => apple [1] => banana [2] => orange )
$query = "key1=value1&key2=value2&key3=value3";
parse_str($query, $params);
$array = explode("&", $query);
print_r($array); // 輸出: Array ( [0] => key1=value1 [1] => key2=value2 [2] => key3=value3 )
$text = "This is an example sentence.";
$words = explode(" ", $text);
print_r($words); // 輸出: Array ( [0] => This [1] => is [2] => an [3] => example [4] => sentence. )
$datetime = "2021-06-01 12:34:56";
$parts = explode(" ", $datetime);
$date = explode("-", $parts[0]);
$time = explode(":", $parts[1]);
echo "Year: " . $date[0] . "\nMonth: " . $date[1] . "\nDay: " . $date[2] . "\nTime: " . $time[0] . ":" . $time[1] . ":" . $time[2];
// 輸出: Year: 2021 Month: 06 Day: 01 Time: 12:34:56
$string = "one|two|three|four";
$array = explode("|", $string);
print_r($array); // 輸出: Array ( [0] => one [1] => two [2] => three [3] => four )
這些案例展示了 explode()
函數在處理字符串時的多種用途。您可以根據需要調整分隔符和字符串內容來滿足您的實際需求。