首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 依單字反轉字串順序

     編輯:PHP 綜合知識

需求:"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 三步驟,快速完成單字級反轉。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved