PHP 的 preg_replace 注意事項

3:59 pm in E-learning by Tsung Hao

PHP 的 preg_match(), preg_replace() 是蠻常用的 regex function, 但是若用變數帶入時, 要特別注意 \ 等 符號. 最常用的就是對字串取代而做 bolding, 若是使用者輸入的是 xxx\, 則有可能會出現下述的錯誤訊息:
  • Warning: preg_replace(): No ending delimiter '/' found
  • Warning: preg_replace(): Compilation failed: missing ) at offset 9

解法

若是外來變數, 要送進 preg_replace / preg_match 前, 先使用 addslashes() 跑過, 再送進去即可.
<?php // 要把 天氣\ => <b>天氣\</b> $html = '今天天氣\\真好'; // 正確文字是 "今天天氣\真好" $kw = '天氣\\'; // 外面參數是輸入 "天氣\" $regkw = addslashes($kw); echo preg_replace("/($regkw)/i", "<b>$1</b>", $html); ?>
Source