萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 字串單字反轉:explode、array_reverse、implode 組合技巧

前言

將字串按單字反轉順序(如 "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)));
}
?>

單字內字元反轉 vs 單字順序反轉

需求函數組合範例
單字順序反轉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"

實務應用範例

1. Yoda 風格說話產生器

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"

2. 搜尋關鍵字權重排序

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())
  • 效能:內建函數組合極快,百萬字串級才需優化
copyright © 萬盛學電腦網 all rights reserved