Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

creating a StringToRegEx function....

Status
Not open for further replies.

karnaf

Programmer
Nov 16, 2002
41
IL
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.

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 (-:

 
the problem is that addslashes and mysql_real_escape_string do not add slashes before . $ ^ [ ] etc. which makes it irrelevant for the regular expression purpose.

karnaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top