需求:"Reversing a string by word" → "word by string a Reversing"。作法:分割成單字陣列 → 反轉陣列 → 合併。
<?php
$s = "Reversing a string by word";
$words = explode(' ', $s); // 1. 以空白分割
$words = array_reverse($words); // 2. 反轉陣列
$s = implode(' ', $words); // 3. 合併
echo $s; // word by string a Reversing
?>
function reverseWordsKeepSpaces($str) {
// 使用正則分割並保留分隔符
$parts = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$words = array_filter($parts, fn($p) => !preg_match('/^\s+$/', $p));
$spaces = array_filter($parts, fn($p) => preg_match('/^\s+$/', $p));
$words = array_reverse($words);
// 重新交錯合併(簡化版)
return implode('', array_merge($words, [''], $spaces)); // 需更精確邏輯
}
function mbReverseWords($str, $encoding = 'UTF-8') {
$words = preg_split('/\s+/u', $str, -1, PREG_SPLIT_NO_EMPTY);
return implode(' ', array_reverse($words));
}
echo mbReverseWords("PHP 字串 反轉 測試"); // 測試 反轉 字串 PHP
善用 explode/array_reverse/implode 三步驟,快速完成單字級反轉。