当然。 preg_match
与/,\s*\w{2,}/
会告诉你:
if (preg_match('/,\s*\w{2,}/', $_POST['location'])) {
//Yep - there's a comma followed by at least two characters in there!
}
尸检:
,
- 文字,
字符
\s*
- 空间/制表/换行符重复0到无限次
\w{2,}
- 任意字母重复2到无限次
看来,你还检查空的。
<?php
$invalid = false;
$split = preg_split('/,\s*/', $_POST['location']);
foreach ($split as $part) {
if (strlen($part) < 2) {
$invalid = true;
break;
}
}
if (!$invalid) {
echo 'Success!';
} else {
echo 'Error!';
}
?>
如果你需要一个正则表达式来为你做这项工作,你可以这样做:
if (preg_match('/^(\w{2,},\s*)*(\w{2,})$/', $_POST['location'])) {
echo 'Success!';
} else {
echo 'Error!';
}
DEMO
OK city,country
ERROR ok, city,country,
ERROR n, foo, bar
ERROR foo, bar, n
ERROR ,foo, bar, test
OK foo,bar
OK foobar
我认为这是对正则表达式 –
它更容易为我们了解你想匹配,当你提供一个例子超值,喜欢'城市,国家什么样的情况下 - >确定,城市,国家, - >坏,...' –
@ZathrusWriter一个正确的格式将是:'城市,国家'这就是为什么只有一个逗号应该被允许,并在该逗号后面的AND之前的字符串。 – AlexioVay