PHP Regular expressions - checking for only numbers and letters, ignore whitespace

Posted on 2011-10-26
Last Modified: 2012-05-12
Hi all,

I have the following:

function isValid($str) {
    return !preg_match('/[^A-Za-z0-9]/', $str);

Open in new window

which works fine with input with no spacing but how can I amend this to ignore whitespacing?

Desired use cases:
'this is a sentance with spaces' returns true
'this is a sentance££ with spaces$$' returns false
'thisisasentancewithnospaces' returns true
'thisisasentance%%%withnospaces' returns false
Question by:dolythgoe
    LVL 11

    Assisted Solution

    by:Ovid Burke

    function isValid($str) {
        return !preg_match('/[^A-Za-z0-9\s*]/', $str);

    Open in new window

    LVL 34

    Accepted Solution

    function isValid($str) {
        return !preg_match('/[^A-Za-z0-9\s]/', $str);

    You don't want an asterisk in there too as it will be treated as a literal asterisk.

    Author Comment

    Thanks guys

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Suggested Solutions

    A colleague recently asked me about how to give his client a small part of the web site that could be completely under the client's control.  Since I have done this sort of thing before to add emergency banners to a web site, I decided I would creat…
    Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    779 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

    12 Experts available now in Live!

    Get 1:1 Help Now