Regular expression: allow alphabets and a comma in between only

Hi,

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.

That’s the same as lauthiamkok posted. lauthiamkok, if ralph.m’s worked then so did your original one.

how can I allow one comma only?

How about

'/[a-zA-Z\\s][COLOR="Red"][\\,]{1}[/COLOR][a-zA-Z\\s]/'

thanks so much! :slight_smile:

Yeah, I’m a noob at this, and it occurred to me later that the original only allowed one instance of the comma. Thanks for clarifying.

this is my final one,

'/^[a-zA-Z\\s]{4,}[\\,]{1}[a-zA-Z\\s]{2,}$/'

or

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

thanks :slight_smile:

This might seem like a silly example, but do you really want to allow "<four spaces>,<two spaces>" (obviously, where <[i]number[/i] spaces> represents whitespace characters)?

I am not sure really. but have a look at the example here,

Plymouth Devon, United Kingdom

so I think I should allow a number of spaces for the input as well. unless there are any incorrect injection I cannot foresee…?