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.
This:
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:Now, to negate a pattern in
[], you use^at the beginning:You could also have used the insensitive modifier
ito match both lowercase (a-z) and uppercase (A-Z):