Carpet
Carpet

Reputation: 519

How to validiate for a solely alphabetic string with spaces in PHP?

I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).

How do I allow alpha characters and spaces, but nothing else?

Upvotes: 5

Views: 4227

Answers (5)

Ricardo Rivera Nieves
Ricardo Rivera Nieves

Reputation: 1465

I would work around with a Simple regex and with the php function preg_match() like this:

if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
  //your code here
}

The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.

Hope this helps someone.

Upvotes: 0

DigiLive
DigiLive

Reputation: 1103

Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...

function validateAlpha($valueToValidate, $spaceAllowed = false) {
    if ($spaceAllowed) {
        $valueToValidate = str_replace(' ', '', $valueToValidate);
    }
    if (strlen($valueToValidate) == 0) {
        return true;
    }
    return ctype_alpha($valueToValidate);
}

Upvotes: 0

dtbarne
dtbarne

Reputation: 8200

$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));

or

$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);

Upvotes: 6

Matt Ball
Matt Ball

Reputation: 359826

if (preg_match("^/[a-zA-Z ]+$/", $input)) {
    // input matches
}

Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php

Upvotes: 2

Israel Unterman
Israel Unterman

Reputation: 13510

ctype_alpha(preg_replace('/\s/', '', $mystring))

The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish

Upvotes: 0

Related Questions