I was trying to create a small function that will convert any given string into a "safe" regular expression by replacing any non alphanumeric character X into a \X (add the backslash before it)
I was counting on the fact that if the non-alphanumeric character is preceded by a backslash, the backslash takes away any special meaning that character might have.
Check the amount of backslashes I needed to add in order to get the desired result.
Example-
Running this function on this string:
[tt][ignore]I'm myemail@server.com & it isn't funny![/ignore][/tt]
will give the following result:
[tt][ignore]/I\'m myemail\@server\.com \& it isn\'t funny\!/is[/ignore][/tt]
It took me a while to figure this one out, so I thought I'd share (-:
I was counting on the fact that if the non-alphanumeric character is preceded by a backslash, the backslash takes away any special meaning that character might have.
Check the amount of backslashes I needed to add in order to get the desired result.
Code:
function StringToRegEx($str)
{
$alnum = "/([^a-z|0-9|\s])/i";
$alnum_convert = "\\\\\${1}";
return "/".preg_replace ($alnum, $alnum_convert, trim($str))."/is";
}
Example-
Running this function on this string:
[tt][ignore]I'm myemail@server.com & it isn't funny![/ignore][/tt]
will give the following result:
[tt][ignore]/I\'m myemail\@server\.com \& it isn\'t funny\!/is[/ignore][/tt]
It took me a while to figure this one out, so I thought I'd share (-: