Remove everything but allowed chars from a string

Posted on 2004-11-10
Last Modified: 2008-02-26

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?

Question by:saimenCH
    LVL 25

    Accepted Solution

    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).

    Author Comment

    Hi Squinky!

    This was exactly the function I was looking for. It works perfect.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now