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

PHP 正則替換函數 ereg_replace 已棄用,請改用 preg_replace:遷移指南與實例

     編輯:PHP 相關知識

重要提示: 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 編譯優化

經典範例遷移對照

範例 1:簡單字串替換

<?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);
?>

範例 2:數字替換文字

<?php
$num = '49';
$string = "this string has four words";
$string = preg_replace('/four/', $num, $string);
echo $string; // this string has 49 words
?>

範例 3:行首行尾插入 (原用 ^ $ 錨點)

<?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。

遷移檢查清單

  1. 所有模式字串加上定界符(推薦 /.../ 或 #...# 避免斜線衝突)。
  2. 檢查模式中是否使用 POSIX 專有字元類別(如 [:alnum:]),改用 PCRE 寫法(\w / [a-zA-Z0-9])。
  3. 替換字串若包含 $n 反向引用或字面 $, \,需用 preg_quote($replacement, $delimiter) 轉義。
  4. 大量替換考慮用 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 (單行模式點匹配換行)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved