php – 只匹配相同语言的字符集(如facebook名称)?

前端之家收集整理的这篇文章主要介绍了php – 只匹配相同语言的字符集(如facebook名称)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
preg_match(???,'firstname lastname') // true;
preg_match(???,'서프 누워') // true;
preg_match(???,'서프 lastname') // false;
preg_match(???,'#$@ #$$#') // false;

目前我使用:

'/^([一-龠0-9\s]+|[ぁ-ゔ0-9\s]+|[ก-๙0-9\s]+|[ァ-ヴー0-9\s]+|[a-zA-Z0-9\s]+|[々〆〤0-9\s]+)$/u'

但它只适用于某些语言.

您需要一个仅匹配来自同一个 unicode script(和空格)的字符的表达式,如:
^([\p{SomeScript} ]+|[\p{SomeOtherScript} ]+|...)$

您可以从脚本列表动态构建此表达式:

$scripts = "Hangul Hiragana Han Latin Cyrillic"; // feel free to add more

$re = [];
foreach(explode(' ',$scripts) as $s)
    $re [] = sprintf('[\p{%s} ]+',$s);
$re = "~^(" . implode("|",$re) . ")$~u";

print preg_match($re,'firstname lastname'); // 1
print preg_match($re,'서프 누워'); // 1
print preg_match($re,'서프 lastname'); // 0
print preg_match($re,'#$@ #$$#'); // 0

但请注意,名称(至少在我熟悉的欧洲脚本中)通常包含属于“常用”脚本而不是特定语言的字符,如点,破折号和撇号.考虑到这些,上述表达式中的“块”的一个更逼真的版本可能是这样的:

((\p{SomeScript}+(\. ?|[ '-]))*\p{SomeScript}+)

这将至少正确验证L.A.Léonde Saint-Just.

一般来说,验证人的姓名是一个复杂的问题,无法以100%的准确度解决.请参阅this funny post及其中的评论,以获取详细信息和示例.

原文链接:https://www.f2er.com/php/131347.html

猜你在找的PHP相关文章