Reputation: 21406
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
Reputation: 10981
$check1 = preg_match('/^[0-9]{1,}$/', $string);
$check2 = preg_match('/^NA$/', $string);
Upvotes: 0
Reputation: 45731
It's pretty simple using a regular expression:
$regExp = '/^(?:[0-9+-]+|NA)$/i';
echo preg_match($regExp, $string) ? 'true' : 'false';
However:
0-9
, -
and +
? This would make the following valid numbers:
NA
and not nA
, Na
and na
, remove the i
at the end of the pattern.Upvotes: 0
Reputation: 455272
if(preg_match('/^(NA|[0-9+-]+)$/',$str)) {
echo "true\n";
} else {
echo "false\n";
}
Upvotes: 3