重要提示: ereg_replace() 自 PHP 5.3.0 起**已棄用**,於 PHP 7.0.0 **完全移除**。現代專案**必須使用 PCRE 兼容的 preg_replace()**。本文將原有 ereg_replace 範例轉換為 preg_replace 寫法,並解釋關鍵差異。
| 特性 | ereg_replace (POSIX 正則) | preg_replace (PCRE 正則) |
|---|---|---|
| 定界符 | 無需定界符 | 必須成對定界符,如 /pattern/, #pattern#, ~pattern~ |
| 特殊字元 | 較少 | 功能豐富(\d, \w, \s, 斷言, 非貪婪等) |
| 大小寫敏感 | 預設敏感 | 預設敏感,可用 i 修飾符忽略 |
| 效能 | 較慢 | **更快**,JIT 編譯優化 |
<?php
// 舊寫法 (ereg_replace)
$num = 'www.jb51.net';
$string = "this string has four words. <br>";
$string = ereg_replace('four', $num, $string);
echo $string; // 輸出: this string has www.jb51.net words. <br>
// 新寫法 (preg_replace) - 模式需加定界符
$string = preg_replace('/four/', $num, $string);
// 若替換字串包含 $ 或 \ 需雙重轉義
$string = preg_replace('/four/', preg_quote($num, '/'), $string);
?>
<?php
$num = '49';
$string = "this string has four words";
$string = preg_replace('/four/', $num, $string);
echo $string; // this string has 49 words
?>
<?php
$string = "測試用文字";
echo "**********$string**********<p>";
// ereg_replace 直接用 ^ $ 作為行首尾
// preg_replace 同樣支援 ^ $,但需定界符
$string = preg_replace('/^/', '<br>', $string); // 行首插入
$string = preg_replace('/$/', '<br>', $string); // 行尾插入
echo "==========$string==========";
// 輸出:
測試用文字
(前後各加一個
)
?>
注意: PCRE 中 ^ 和 $ 預設匹配**字串**開頭結尾。若需匹配**多行**模式下的每行開頭結尾,需加 m 修飾符:/^/m, /$/m。
/.../ 或 #...# 避免斜線衝突)。[:alnum:]),改用 PCRE 寫法(\w / [a-zA-Z0-9])。$n 反向引用或字面 $, \,需用 preg_quote($replacement, $delimiter) 轉義。str_replace() 或 strtr()(非正則),效能提升數倍。str_replace/strtr原文範例皆為**固定字串替換**,完全無需正則引擎開銷:
<?php
$string = "this string has four words";
$string = str_replace('four', 'www.jb51.net', $string); // 最快、最簡潔
// 多組同時替換
$string = strtr($string, [
'four' => '49',
'words' => 'terms',
]);
?>
原則: 能用 str_replace/strtr 解決的,絕不動用 preg_replace。
ereg_replace 已成歷史,現有代碼**必須遷移**。str_replace/strtr,效能與可讀性雙贏。preg_replace,善用修飾符 i (忽略大小寫)、m (多行)、s (單行模式點匹配換行)。