LoginSignup
16
15

More than 5 years have passed since last update.

正規表現でバックスラッシュをマッチさせる際の注意

Last updated at Posted at 2013-10-18
エラー
mb_ereg_replace("\\", "\\\\", $string);
Warning: mb_ereg_replace(): mbregex compile err: end pattern at escape

正規表現を利用してバックスラッシュをマッチさせる際は、検索文字を2重にエスケープする必要があります。

正常
mb_ereg_replace("\\\\", "\\\\", $string);

一応マニュアルにも書いてあることですが、うっかりハマりがちではあります。

PHP:エスケープシーケンス - Manual

シングルクォートあるいはダブルクォートで囲まれた PHP の 文字列 の中では、バックスラッシュは特別な意味を表します。 そのため、正規表現 \\ を使用して \ とマッチさせたい場合は PHP のコード内では "\\\\" あるいは '\\\\' と記述する必要があります。

16
15
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15