php正则表达式为空格

i would like to validate user inputs like this: "Ahmedabad Intl-Ahmedabad, India(AMD)", The first letter is capital and there can be space and - in the first part. and then one comma with one space, and then some letters with '(' letters ')'. I have tried it like this:

preg_match('/^([a-zA-Z- ]+), ([a-zA-Z]+)([A-Z()]+)/', $string),

Does anyone know why it does not work? thanks

You need to add backslash to the parenthesis. Try this:

$string = "Ahmedabad Intl-Ahmedabad, India(AMD)";
echo  preg_match('/^[a-zA-Z- ]+, [a-zA-Z]+\([A-Z]+\)/', $string); //1

$string = "Ahmedabad Intl-Ahmedabad, India(AMD";
echo  preg_match('/^[a-zA-Z- ]+, [a-zA-Z]+\([A-Z]+\)/', $string); //0
<?php

$foo = "Dave Smith";
$bar = "SamSpade";
$baz = "Dave\t\t\tSmith";

var_dump(preg_match('/\s/',$foo));
var_dump(preg_match('/\s/',$bar));
var_dump(preg_match('/\s/',$baz));

Output

int(1)
int(0)
int(1)

see: https://stackoverflow.com/questions/1161708/php-detect-whitespace-between-strings

You can use this:

if (preg_match('~^[A-Z][a-z]*+(?>[ -][A-Z][a-z]*)*+, [A-Z][a-z]*\([A-Z]+\)$~', $string)) {
    // true
} else {
    // false
}