Re: Is there a faster way to escape special characters in a regex?
| From: | Lars Torben Wilson | Date: | Tue, 12 Mar 2002 20:47:29 +0000 |
| Subject: | Re: Is there a faster way to escape special characters in a regex? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-88234@lists.php.net to get a copy of this message | ||
On Tue, 2002-03-12 at 05:57, Richard Davey wrote:
> Hi all,
>
> At the moment I'm doing this to escape all "special" regular expression
> characters from my regex string:
Sounds like you want preg_quote():
http://www.php.net/manual/en/function.preg-quote.php
Hope this helps,
Torben
> $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
--
Torben Wilson <torben@php.net>
http://www.thebuttlesschaps.com
http://www.hybrid17.com
http://www.inflatableeye.com
+1.604.709.0506