Last active
July 11, 2023 20:52
-
-
Save elenakondrateva/8d387bc1b9299f950cf8731ba3fbdfa9 to your computer and use it in GitHub Desktop.
Escape REGEXP for MariaDB query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// MariaDB uses the C escape syntax in strings (for example, "\n" to represent the newline character), | |
// we must double any "\" that we use in REGEXP strings (see https://mariadb.com/kb/en/regexp/) | |
// PHP's preg_quote() won't work here as it adds single slashes so use a special regular expression here | |
$string = 'My [string] {with} ~regexp~ |special| /characters/+.'; | |
$pattern = '/(\+|-|\||&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/'; | |
$replacement = '\\\\\\\\${1}'; | |
$stringEscaped = preg_replace($pattern, $replacement, $string); | |
// use string in MariaDB REGEXP functions | |
$query = <<<SQL | |
SELECT * FROM my_table | |
WHERE my_column REGEXP '{$stringEscaped}' | |
SQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment