PHP RegEx specifies the characters I want?

How would I remove all characters from a string that does NOT contain [a-zA-Z0-9\-\/_]

:?

In other words, I would like to indicate what I want, not what I don't have. Thanks.

+2


a source to share


4 answers


The easiest way:

preg_replace("/[^a-zA-Z0-9-\/_]/", '', $string);

      



Another approach would be to do the match and then explode the matched values.

+5


a source


try the following



preg_replace("/[^a-zA-Z0-9-\/_]/", "", $string);

      

+1


a source


If you want to keep "/" and "\"

preg_replace("/[^a-zA-Z0-9-\\\/_]/", '', $string);

      

0


a source


The shortest way to do it:

echo(preg_replace('~[^\w-/]~i', '', 'H#el/-l0:0.'));

      

Outputs:

"Hel/-l00"

      

0


a source







All Articles