萬盛學電腦網

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

PHP 替換字串中第 N 次出現的字元/子字串:非正則與正則兩種實作

PHP 精確替換第 N 次出現的子字串:自訂函數與正則方案

PHP 內建 str_replace、preg_replace 均為**全域替換**。若需「只替換第 3 次出現的 'hello'」,需自行實作。

方案一:純 PHP 字串操作 (不使用正則,效能佳、可讀性高)

<?php
/**
 * 替換字串中第 $n 次出現的 $search 為 $replace
 *
 * @param string $haystack 原字串
 * @param string $search   目標子字串
 * @param string $replace  替換字串
 * @param int    $n        第 N 次 (從 1 開始),<=0 視為不替換
 * @return string|false    替換後字串,若 $n 超過出現次數回傳 false
 */
function replaceNth(string $haystack, string $search, string $replace, int $n): string|false {
    if ($n <= 0) return $haystack;
    $len = strlen($search);
    if ($len === 0) return $haystack;

    $pos = -1;
    for ($i = 1; $i <= $n; $i++) {
        $pos = strpos($haystack, $search, $pos + 1);
        if ($pos === false) return false; // 找不到第 N 次
    }
    // 找到第 N 次位置 $pos,進行替換
    return substr_replace($haystack, $replace, $pos, $len);
}

// 測試
$text = 'hello world hello pig hello cat hello dog hello small boy';
echo replaceNth($text, 'hello', 'good-bye', 3);
// 輸出: hello world hello pig good-bye cat hello dog hello small boy
?>
  • 使用 strpos 迴圈定位第 N 次位置,再用 substr_replace 精確替換。
  • 不支援正則模式;若需正則請見方案二。
  • 回傳 false 表示出現次數不足。

方案二:正則表達式 + 回調函數 (支援模式、更靈活)

<?php
/**
 * 使用 preg_replace_callback 替換第 N 次匹配
 */
function pregReplaceNth(string $pattern, string $replace, string $subject, int $n, int $flags = 0): string {
    if ($n <= 0) return $subject;
    $count = 0;
    return preg_replace_callback($pattern, function($m) use (&$count, $n, $replace) {
        $count++;
        return $count === $n ? $replace : $m[0];
    }, $subject, 1, $flags); // limit=1 只替換一次 (由回調控制)
}

// 測試:替換第 2 個數字序列
$str = 'Order 1234, Item 567, Code 89';
echo pregReplaceNth('/\d+/', 'XXX', $str, 2); // Order 1234, Item XXX, Code 89
?>
  • preg_replace_callback 的 $count 參數 (PHP 5.1+) 這裡用不到,因 limit=1 只會呼叫一次回調;改用閉包捕獲計數器。
  • 模式可為任意 PCRE 正則。

常用字串替換函數快速選擇表

函數支援正則大小寫特點適用場景
str_replace否敏感字串/陣列批量替換,最快固定字串全域替換
str_ireplace否**不敏感**支援陣列批量不分大小寫固定字串替換
substr_replace否敏感指定位置/長度替換已知位置替換 (如插入、截斷)
preg_replace**是**敏感 (可 i 修飾符)子模式引用 $1、回調、限制次數複雜模式替換、結構化轉換
preg_replace_callback**是**敏感回調函數動態決定替換內容條件替換、計數替換、動態計算
strtr否敏感單字元/子字串映射,**單次掃描**最快字元轉換、多鍵值單次替換

正則替換常見模式範例

<?php
// 1. 移除所有標點/分隔符 (中英文)
$regex = '/[,,。.、;;||\s]+/u';
$str = '河北,石家莊,北京,上海|天津|重慶,,,河南';
echo preg_replace($regex, ' ', $str); // 河北 石家莊 北京 上海 天津 重慶 河南

// 2. HTML 標籤屬性雙引號統一
$html = '
'; echo preg_replace('/(\w+)=([\'"]?)(.*?)\\2/', '$1="$3"', $html); //
// 3. 回調動態計算:將價格含稅 $priceStr = 'Price: $100, $200, $50'; echo preg_replace_callback('/\$(\d+)/', function($m) { return '$' . round($m[1] * 1.05, 2); }, $priceStr); // Price: $105, $210, $52.50 ?>
copyright © 萬盛學電腦網 all rights reserved