PHP 內建 str_replace、preg_replace 均為**全域替換**。若需「只替換第 3 次出現的 'hello'」,需自行實作。
<?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 只會呼叫一次回調;改用閉包捕獲計數器。| 函數 | 支援正則 | 大小寫 | 特點 | 適用場景 |
|---|---|---|---|---|
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 ?>
- 上一篇程序編程: PHP 錯誤顯示與日誌記錄設定:display_errors、log_errors 完整指南
- 下一篇程序編程: PHP 位運算詳解:從基礎運算到錯誤報告實戰應用