將字串按單字反轉順序(如 "Hello World" → "World Hello")是常見文字處理需求。PHP 以 explode() 分割、array_reverse() 反轉、implode() 合併三步驟優雅解決。
<?php
$s = "Reversing a string by word";
// 1. 以空白分割為陣列
$words = explode(' ', $s);
// ['Reversing', 'a', 'string', 'by', 'word']
// 2. 反轉陣列順序
$words = array_reverse($words);
// ['word', 'by', 'string', 'a', 'Reversing']
// 3. 以空白合併回字串
$s = implode(' ', $words);
// "word by string a Reversing"
echo $s;
?>
explode(' ', $str) 會合併連續空白,若需保留原始間距:
<?php
function reverseWordsPreserveSpaces(string $str): string {
// 使用正則分割,保留分隔符
$parts = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
// ['Reversing', ' ', 'a', ' ', 'string', ' ', 'by', ' ', 'word']
// 只反轉非空白部分
$words = array_filter($parts, fn($p) => $p !== '' && !ctype_space($p));
$reversedWords = array_reverse($words);
// 重建:遍歷原始 parts,遇到單字取反轉後的,空白保留
$wordIndex = 0;
$result = '';
foreach ($parts as $part) {
if ($part !== '' && !ctype_space($part)) {
$result .= $reversedWords[$wordIndex++];
} else {
$result .= $part;
}
}
return $result;
}
echo reverseWordsPreserveSpaces("Hello world\tPHP");
// "PHP world\tHello"(保留多重空白與 tab)
?>
<?php
function reverseWordsMultilingual(string $str): string {
// 使用 Unicode 文字斷詞(需 intl 擴展)
if (class_exists('IntlBreakIterator')) {
$bi = IntlBreakIterator::createWordInstance();
$bi->setText($str);
$words = [];
$positions = [];
foreach ($bi as $offset) {
$positions[] = $offset;
}
// 提取單字(略過空白/標點)
for ($i = 0; $i < count($positions) - 1; $i++) {
$start = $positions[$i];
$end = $positions[$i + 1];
$word = mb_substr($str, $start, $end - $start);
if (preg_match('/\p{L}/u', $word)) { // 含字母
$words[] = $word;
}
}
$reversed = array_reverse($words);
// 重建邏輯較複雜,此處略...
return implode(' ', $reversed); // 簡化版
}
// 降級:以空白分割
return implode(' ', array_reverse(explode(' ', $str)));
}
?>
| 需求 | 函數組合 | 範例 |
|---|---|---|
| 單字順序反轉 | implode(' ', array_reverse(explode(' ', $str))) | "a b c" → "c b a" |
| 每個單字內字元反轉 | implode(' ', array_map('strrev', explode(' ', $str))) | "abc def" → "cba fed" |
| 整個字串字元反轉 | strrev($str) | "abc def" → "fed cba" |
| 單字順序 + 字元都反轉 | strrev(implode(' ', array_reverse(explode(' ', $str)))) | "a b c" → "c b a" → "a b c" |
function yodaSpeak(string $sentence): string {
$words = explode(' ', $sentence);
// 簡單版:動詞移到最後
$verbs = ['is', 'am', 'are', 'was', 'were', 'have', 'has', 'do', 'does', 'did'];
$verbIndex = null;
foreach ($words as $i => $w) {
if (in_array(strtolower($w), $verbs)) {
$verbIndex = $i;
break;
}
}
if ($verbIndex !== null) {
$verb = array_splice($words, $verbIndex, 1);
$words = array_merge($words, $verb);
}
return implode(' ', $words);
}
echo yodaSpeak("You are strong"); // "You strong are"
echo yodaSpeak("I have the force"); // "I the force have"
function highlightKeywords(string $text, array $keywords): string {
$words = explode(' ', $text);
// 將包含關鍵字的單字移到前面
usort($words, function($a, $b) use ($keywords) {
$aMatch = (int)preg_match('/' . implode('|', $keywords) . '/i', $a);
$bMatch = (int)preg_match('/' . implode('|', $keywords) . '/i', $b);
return $bMatch - $aMatch; // 符合的優先
});
return implode(' ', $words);
}
<?php
$str = str_repeat("word ", 10000); // ~50KB
// 方法 1:explode + array_reverse + implode
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
implode(' ', array_reverse(explode(' ', $str)));
}
echo "explode/reverse/implode: " . (microtime(true) - $start) . "s\n";
// 方法 2:preg_split + array_reverse + implode
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
implode(' ', array_reverse(preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY)));
}
echo "preg_split: " . (microtime(true) - $start) . "s\n";
// 通常 explode 版本較快(單一字元分隔符)
?>
explode() → array_reverse() → implode()preg_split('/(\s+)/', ..., PREG_SPLIT_DELIM_CAPTURE)IntlBreakIterator 正確斷詞strrev())