PHP function to escape MySQL regexp syntax

蹲街弑〆低调 提交于 2019-12-03 18:08:01

问题


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

Any ideas?


回答1:


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.)




回答2:


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




回答3:


There's no native MySQL function for that. You might just need to use preg_quote before passing the regular expression to the MySQL query.




回答4:


Try this: (PHP)

    $tags="test'*\\\r blue";
    $tags=mysql_real_escape_string($tags);
    $tags=preg_replace('/([.*?+\[\]{}^$|(\)])/','\\\\\1',$tags);
    $tags=preg_replace('/(\\\[.*?+\[\]{}^$|(\)\\\])/','\\\\\1',$tags);



回答5:


Thank @bobince's good answer. But it has a problem if you need to use mysql_real_escape_string after quoting, that I mentioned it in a comment.

Actually preg_quote and mysql_real_escape_string have overlap and it makes this problem! mysql_real_escape_string must not escape \ in this case. So I suggest:

function regexpEscape(/*string*/ $input) { // Uncomment `string` for PHP 7.0+
    return addcslashes(preg_quote($input), "\0'\"\n\r\x1A"); // charlist = All characters that escape by real_escape_string except backslash
}

(For charlist see: http://php.net/manual/en/mysqli.real-escape-string.php)

I know this is not an ideal way, but couldn't find a better way.



来源:https://stackoverflow.com/questions/4024188/php-function-to-escape-mysql-regexp-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!