Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to escape MySQL regexp syntax

I'm looking for something similar to preg_quote, but for the MySQL regexp syntax.

Any ideas?

like image 397
akosch Avatar asked Oct 26 '10 13:10

akosch


2 Answers

MySQL regexps are the ‘extended’ POSIX variant (ERE), available in PHP as the deprecated ereg_ functions.

Unfortunately there is no ereg_quote in PHP, however PCRE's special characters are a superset of ERE's special characters, and backslash-escaping a non-special punctuation character doesn't harm it, so you can get away with using preg_quote safely.

(Naturally you will need parameterised queries or mysql_real_escape_string after that quoting, to stop the backslashes being misinterpreted as MySQL's non-ANSI-standard string literal escapes.)

like image 82
bobince Avatar answered Sep 30 '22 16:09

bobince


Sadly, PHP's preg_quote() messes up MySQL REGEXP by escaping a colon sign (:) which MySQL's REGEXP does not understand

like image 35
ElectroNick Avatar answered Sep 30 '22 14:09

ElectroNick