Alfred
Alfred

Reputation: 21406

validating only selected characters in string php (phone number validation)

i have a string containing alpha numeric characters. The script should return (echo) "true" if the string contains only 0-9, - , + , or the word NA (NA should be validated only if it contain no other characters and should echo false if the string contain any other character along with "NA"), The script should echo "false" if the string contains any other characters other than the specified characters.. How can i make this possible??

Thanks in advance.. :)

blasteralfred

Upvotes: 1

Views: 2091

Answers (3)

yoda
yoda

Reputation: 10981

$check1 = preg_match('/^[0-9]{1,}$/', $string);
$check2 = preg_match('/^NA$/', $string);

Upvotes: 0

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45731

It's pretty simple using a regular expression:

$regExp = '/^(?:[0-9+-]+|NA)$/i';
echo preg_match($regExp, $string) ? 'true' : 'false';

However:

  • Are you sure you just want to ensure that the string contains 0-9, - and +? This would make the following valid numbers:
    • -9+9291---
    • +2039-291919++0203-19293
  • If you only want to match NA and not nA, Na and na, remove the i at the end of the pattern.

Upvotes: 0

codaddict
codaddict

Reputation: 455272

if(preg_match('/^(NA|[0-9+-]+)$/',$str)) {
        echo "true\n";
} else {
        echo "false\n";
}

Upvotes: 3

Related Questions