I am using this code for checking for a proper phone number.
Code:
$string_exp = "^[0-9 .-]+$";
I would also like to have the string be acceptable if they entered the characters N/A in place of a phone number. Can someone tell me how to change this expression to accept these three additional characters as an "or" statement to the phone number characters?
I don't fully understand the finer points of regular expressions, and haven't been able to figure this one out.
You could do it as part of the regex, I suppose (adjusted for use with the preg_*() functions, which you should be using instead of ereg_*()?):
PHP Code:
"#^(N/A|[0-9 .-])$#i"
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Parentheses enclose a sub-pattern, which is evaluated first (just like parentheses in PHP) and can have repetition modifiers append after the closing paren (not used in this case).
"|" is the "or" operator, so it matches if either side of the "|" matches.
I used "#" as the pattern delimiter, but it can be any of most special characters -- but you then have to escape that character within the pattern with a back-slash if you want that literal character to match. The "i" following the closing "#" makes the whole pattern case-Insensitive, so "N/A" or "n/a" would both match.
The "^" anchors the pattern to the start of the string, and the "$" to the end of the string.
[] is used to define a "character class": it matches on any of the characters or ranges of characters it contains. I used a "+" repetition modifier after it, meaning to match on one or more instances of those characters. ("*" would be used if you wanted to match on zero or more instances.)
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks