preg_match() to match either of the given condition
yesterday I got some help here to get the regular expression right to accept the input such as,
Plymouth, United Kingdom
but I realised that I should accept such input below as well,
Plymouth, Devon开发者_如何转开发, United Kingdom
so I added another expression in the code below and now it cannot accept either of the condition above! what have I done wrong?
if(!preg_match('/^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{4,}$/', $mem_town_city_country) || !preg_match('/^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{2,}[\,]{1}[a-zA-Z\s]{4,}$/', $mem_town_city_country))
{
$error = true;
echo '<error elementid="mem_town_city_country" message="TOWN/CITY, COUNTRY - sorry, they appear to be incorrect."/>';
}
how can I make it to accept the input either
Plymouth, United Kingdom
or,
Plymouth, Devon, United Kingdom
?
Change the ||
to &&
. The current code will show the error message if either the first regex or the second regex is not matched. You want the error message to show only if both regexes do not match.
if(!preg_match('/^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{4,}$/', $mem_town_city_country) && !preg_match('/^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{2,}[\,]{1}[a-zA-Z\s]{4,}$/', $mem_town_city_country))
Alternatively, you can use regex alternation to combine the two:
if(!preg_match('/(^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{4,}$|^[a-zA-Z\s]{4,}[\,]{1}[a-zA-Z\s]{2,}[\,]{1}[a-zA-Z\s]{4,}$)/', $mem_town_city_country))
Of course, it's possible to shorten this, but in the above code sample I am trying to show the concept rather than making the code as concise as possible
Or you can use the one regex, that do all the work:
$input = 'Plymouth, Devon, United Kingdom';
$matched = preg_match('~^[a-z\s]{4,}(?:,[a-z\s]{4,}){1,2}$~i', $input, $matches);
var_dump($matched, $matches);
精彩评论