Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping out characters that aren't a-zA-Z0-9, _ and - from PHP strings

I want to stop out all characters that do NOT match this regex pattern: [a-zA-Z0-9_-].

Usually I would do this:

preg_replace("[a-zA-Z0-9_-]", "", $var);

but obviously this has the oposite effect to what I want. Is there a NOT in regex? How can I get this to strip out any characters that do not match the pattern?

Thanks.

like image 223
Josh Avatar asked Dec 08 '25 06:12

Josh


1 Answers

This:

preg_replace("[a-zA-Z0-9_-]", "", $var);

wouldn't even replace those characters, except if the input string is exactly the pattern. By using [] as delimiters, they have not the same effect as their would in the expression itself. You could change your delimiter (e.g.: /), or add some more brackets in the pattern:

preg_replace("/[a-zA-Z0-9_-]/", "", $var);    // this works
preg_replace("[[a-zA-Z0-9_-]]", "", $var);    // this too

Now, to negate a pattern in [], you use ^ at the beginning:

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

You could also have used the insensitive modifier i to match both lowercase (a-z) and uppercase (A-Z):

preg_replace("/[^a-z0-9_-]/i", "", $var);   // same as above
like image 178
netcoder Avatar answered Dec 09 '25 20:12

netcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!