Is there a faster way to escape special characters in a regex?
| From: | Richard Davey | Date: | Tue, 12 Mar 2002 13:57:56 +0000 |
| Subject: | Is there a faster way to escape special characters in a regex? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-88196@lists.php.net to get a copy of this message | ||
Hi all,
At the moment I'm doing this to escape all "special" regular expression
characters from my regex string:
$badwordtest = str_replace("/","",$badwordtest);
$badwordtest = str_replace("\\","",$badwordtest);
$badwordtest = str_replace("^","\^",$badwordtest);
$badwordtest = str_replace(".","\.",$badwordtest);
$badwordtest = str_replace("[","\[",$badwordtest);
$badwordtest = str_replace("$","\$",$badwordtest);
$badwordtest = str_replace("(","\(",$badwordtest);
$badwordtest = str_replace(")","\)",$badwordtest);
$badwordtest = str_replace("|","\|",$badwordtest);
$badwordtest = str_replace("*","\*",$badwordtest);
$badwordtest = str_replace("+","\+",$badwordtest);
$badwordtest = str_replace("?","\?",$badwordtest);
$badwordtest = str_replace("{","\{",$badwordtest);
$badwordtest = str_replace("}","\}",$badwordtest);
$badwordtest = str_replace("\\","\\",$badwordtest);
$badwordtest = "/" . $badwordtest . "/i";
if (preg_match($badwordtest,$word)) {
$directmatch = TRUE;
}
Is there a way to either do this all in one go or even better, have the ereg
itself ignore those characters if they are contained in the string? The idea
is that I want to check a word for swearing by doing a direct comparison
with a list of swear words, however the word I check could easily contain a
special character so I need to escape it before the test commences.
Suggestions very welcome!
Cheers,
Richard
--
Fatal Design
http://www.fatal-design.com
Atari / DarkBASIC / Coding / Since 1995