This RegEx is for cleanup user input from a search form

$query = preg_replace("/[^A-Za-z0-9 _.,*&-]/", ' ', $query);

I need to add the slash as a valid character too, but if I add it, I get an error. I assume I have to escape it but can't find how to do that

$query = preg_replace("/[^A-Za-z0-9 _.,*&-/]/", ' ', $query); // doesn't works
$query = preg_replace("/[^A-Za-z0-9 _.,*&-//]/", ' ', $query); // doesn't works
$query = preg_replace("/[^A-Za-z0-9 _.,*&-\/]/", ' ', $query); // doesn't works

Using php

Comments

With php-5.1.6 at least, your last example (...\/]/") runs happily.

Written by Greg Bacon

Accepted Answer

You can use something other then the / as your delimiter - try something like this:

$query = preg_replace("%[^A-Za-z0-9 _.,*&-/]%", ' ', $query);

Kobe also posted the correct way to escape in that situation, but I find the regex stays more readable when I switch the delimiter to something I'm not using in the expression, when possible.

EDIT

A bit of additional information can be found at http://www.php.net/manual/en/regexp.reference.delimiters.php (quoting it here:)

"When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character."

Written by Erik
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki