During my programming work I had to do some system administration tasks, and since a while I'm also maintaining some servers. This is a log for the problems I find - and hopefully their solutions.

Wednesday, April 06, 2005

Backslashes in php regular expressions

Damn this was frustrating! Trying to match a \ character in php? Don't expect the usual Perl behavior, finding \\ - it won't work. You have to search for \\\ ! And the solution was only found in a source code with google:
  function deslash($content) {
// Note: \\\ inside a regex denotes a single backslash.

// Replace one or more backslashes followed by a single
// quote with a single quote.
$content = preg_replace("/\\\+'/", "'", $content);

// Replace one or more backslashes followed by a double
// quote with a double quote.
$content = preg_replace('/\\\+"/', '"', $content);

// Replace one or more backslashes with one backslash.
$content = preg_replace("/\\\+/", "\\", $content);

return $content;
}
2 hours wasted...

0 Comments:

Post a Comment

<< Home