Search code examples
phpregexpreg-match

regular expression: allow alphabets and a comma in between only


I want to let the user input their own town/city and country, so I want to allow alphabets and a comma only in between city and country, below is what I came up with but it doesn't work with the second expression

'/[a-zA-Z\s]\,[a-zA-Z\s]/'

the first one is imperfect, bcos it allow as many commas as you want to put in,

'/^[a-zA-Z\s\,]+$/'

if(!preg_match('/^[a-zA-Z\s\,]+$/', $mem_town_city_country) || !preg_match('/[a-zA-Z\s]\,[a-zA-Z\s]/', $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 allow one comma only?

also, not sure if this is too much - can I check the character input for the city, for instance at least 3, and at least 4 for the country?

thanks.


Solution

  • You were close. Try this:

    /^[a-zA-Z\s]+\,[a-zA-Z\s]+$/
    

    For the number of characters requirement:

    /^[a-zA-Z\s]{3,}\,[a-zA-Z\s]{4,}$/