Remove everything but allowed chars from a string


I've got a URL like this:

I if there's something different than a-z, 0-9, _ or "-" in the variable "show", then it should be stripped.

some examples:
show=123 => show=123
show=../abc => show=abc
show=!?x+ => show=x
show=a-b_c => show=a-b_c

Is there a built-in php function that does something like that?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marcus BointonCommented:
usual way to clean data like this is with a regex:

$var = preg_replace('/[^a-z0-9_-]/', '', $var);

That pattern says: replace anything in $var that's not a-z, 0-9 _ or - with nothing (i.e. delete it).

The - must be the first or last char in the match list so it doesn't get interpreted as a range delimiter (as in a-z).

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
saimenCHAuthor Commented:
Hi Squinky!

This was exactly the function I was looking for. It works perfect.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.