对于我的 PHP 脚本,我有以下代码:
if (!preg_match("/[^A-Za-z]/", $usersurname))
$usersurname_valid = 1;
这一直有效,直到我意识到一个姓氏可以是两个或更多的词...... doh。
如果我想在两个世界之间允许 1 个空间,任何人都可以告诉我如何编写此代码?例如:
Jan Klaas 现在错了,应该允许 Jan Klaas 和 Jan Klaas Martijn 等等。
更好的是 preg 替换,用 1 替换两个或多个空格,所以当你写:
Jan(space)(space)Klaas 或 Jan(space)(space)(space)(space)Klaas 时,它会返回 Jan (空格)克拉斯。
我搜索了一段时间,但不知何故我无法让这个空间匹配工作..
PS:当我得到这个工作时,我当然也会将这个应用于中间名和姓氏。
============================================
编辑:在你帮助我之后,我将我的代码重新编写为:
// validate usersurname
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usersurname))
$usersurname_valid = 1;
// validate usermidname
$usermidname = preg_replace("/\s{2,}/"," ", $usermidname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usermidname))
$usermidname_valid = 1;
// validate userforename
$userforename = preg_replace("/\s{2,}/"," ", $userforename);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$userforename))
$userforename_valid = 1;
和错误通知
elseif ($usersurname_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the last name. $usersurname $usermidname $userforename</p>");
// usermidname character validation
elseif ($usermidname_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the middle name. $usersurname $usermidname $userforename</p>");
// userforename character validation
elseif ($userforename_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the (EDIT) first name. $usersurname $usermidname $userforename</p>");
替换空格效果很好,我需要这个 preg_match 来检查 A-Za-z + 空格。我认为在这种情况下,它是否匹配超过 1 个空格并不重要,因为它无论如何都会被替换,对吧?
编辑:
我的情况的解决方案:
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/[^A-Za-z ]/", $usersurname))
这完成了工作。感谢您的帮助,J0HN