PHP, check string for invalid character?

Posted on 2007-08-12
Last Modified: 2012-08-14
How can I check if a string contains symbols or weird characters like !@#$%^%^&&*(())-+=?><,.'"}{[]| etc?
Question by:jtcy
    LVL 16

    Accepted Solution

    A better way to do things is to check that a string only contains the characters that are allowed. This is known as using a whitelist. Checking for illegal characters is known as using a blacklist. A whitelist is much easier to maintain than a blacklist.

    Using regular expressions is a quick and easy way to check for character classes, so take a look at preg_match in the PHP documentation.

    For instance, if your string only permitted letters, digits and standard spaces, you could use this to check that the string was valid:

    $valid = preg_match('/^[a-z0-9 ]+$/', $string);

    This does not allow an empty string, but if you change the + to a * the empty string will be permitted. If the string is valid, then $valid will equal true.

    Regular expressions are not easy to grasp at first, but they are very powerful for string validation and manipulation.
    LVL 29

    Assisted Solution

    Fortunately, there are libraries of well defined regular expressions from which to start with, so it isn't so intimidating.

    Is an excellent place to start.
    LVL 1

    Expert Comment

    Forced accept.

    EE Admin

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    When it comes to showing a 404 error page to your visitors, you do not want that generic page to show, and you especially do not want your hosting provider’s ad error page to show either. In this article, I will show you how to enable the custom 40…
    Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
    This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
    This video teaches users how to migrate an existing Wordpress website to a new domain.

    729 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

    21 Experts available now in Live!

    Get 1:1 Help Now