字串替換是內容處理、模板渲染、資料清洗的高頻操作。PHP 提供多層次替換函數,從簡單全域替換到位置精確控制、正則模式替換,覆蓋各類場景。
| 函數 | 替換模式 | 大小寫敏感 | 支援陣列 | 位置控制 | 正則支援 |
|---|---|---|---|---|---|
str_replace() | 全域 | 是 | 是 | 否 | 否 |
str_ireplace() | 全域 | 否 | 是 | 否 | 否 |
substr_replace() | 指定位置/長度 | 是 | 是 | 是 | 否 |
strtr() | 字符/子字串映射 | 是 | 是(映射陣列) | 否 | 否 |
preg_replace() | 正則模式 | 可控 | 是 | 否 | 是 |
<?php
$str = "Welcome to www.Example.COM!";
echo str_ireplace('com', 'net', $str);
// Welcome to www.Example.NET!
// 關鍵字高亮(搜尋結果描紅)
$keyword = 'php';
$text = 'PHP 是最好的語言,php 很流行';
$highlighted = str_ireplace($keyword, "$keyword", $text);
echo $highlighted;
?>
<?php
$str = "Welcome to www.example.com!";
// 從索引 11 開始替換到結尾
echo substr_replace($str, 'China', 11);
// Welcome to China
// 替換指定長度:索引 11,長度 15 替換為 China
echo substr_replace($str, 'China', 11, 15);
// Welcome to China!
// 陣列批量:多個位置同時替換
$arr = ['Hello A', 'Hello B', 'Hello C'];
echo substr_replace($arr, 'Hi', 6);
// ['Hi A', 'Hi B', 'Hi C']
?>
<?php
// 字符映射:單字符替換
echo strtr('hello', 'el', 'ip'); // hippo
// 子字串映射表(長者優先匹配)
$trans = [
'Hello' => 'Hi',
'world' => 'PHP',
'Hi' => 'Hey' // 不會二次替換
];
echo strtr('Hello world', $trans); // Hi PHP
?>
<?php
// 隱藏手機中間 4 位
$phone = '13812345678';
echo preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $phone);
// 138****5678
// 多行標準化空白
$text = "Line1\n\n\nLine2\t\tLine3";
echo preg_replace('/\s+/', ' ', $text); // Line1 Line2 Line3
// 回調函數動態替換
echo preg_replace_callback('/\b(\w+)\b/', function($m) {
return strtoupper($m[1]);
}, 'hello world'); // HELLO WORLD
?>
<?php
function render($template, $data) {
return preg_replace_callback('/\{\{(\w+)\}\}/', function($m) use ($data) {
return $data[$m[1]] ?? $m[0];
}, $template);
}
$tpl = 'Hello {{name}}, welcome to {{site}}!';
$data = ['name' => 'John', 'site' => 'Example.com'];
echo render($tpl, $data); // Hello John, welcome to Example.com!
?>
str_replace() / str_ireplace()substr_replace()strtr()preg_replace()替換操作看似簡單,但大數據量下效能差異巨大:strtr() 單次掃描優於多次 str_replace(),正則最靈活但最慢,按需選擇。