我想制作一个函数来检测/验证一个字符串至少有 2 个单词,并且每个单词至少有 2 个字母(除了这两个字母,它可以包含任何其他字符 {without numbers},但我不关心哪个和多少)。
现在,我不确定我是否应该为此使用正则表达式或者我可以用其他方式做到这一点。
如果我需要为它制作正则表达式,我也不知道该怎么做,因为我需要检查所有可用的字母。
这是我现在得到的正则表达式 [A-Za-z]{2,}(\s[A-Za-z]{2,})
验证 2 个单词和 2 个字母至少在每个单词中。
编辑: 重新考虑后,我决定支持大多数语言,因为 kr-jp-cn 语言与其他语言的工作方式不同。我的主要规则不会让 kr-jp-cn 字母算作字母,而是算作字符。
编辑 2:
这是我基于@message 回答使用的函数。
function validateName($name)
{
if (strcspn($name, '0123456789') == strlen($name)) //return the part of the string that dont contain numbers and check if equal to it length - if it equal than there are no digits - 80% faster than regex.
{
$parts = array_filter(explode(' ',$name)); //should be faster than regex which replace multiple spaces by single one and then explodes.
$partsCount = count($parts);
if ($partsCount >= 2)
{
$counter = 0;
foreach ($parts as $part)
{
preg_match_all('/\pL/u', $part, $matches);
if (count($matches[0]) >= 2)
{
$counter++;
}
}
}
if ($counter == $partsCount)
{
return 'matches';
}
}
return 'doesnt match';
}
感谢您的帮助。
最佳答案
我也会使用正则表达式
preg_match('/\w{2,}\s+\w{2,}/u', 'word слово');
\w{2,}
匹配单词字符 2 个或更多。
\s+
匹配之间的所有空格
并使用 /u
unicode modifier
编辑:
我认为这样的解决方案会有所帮助,但你需要一些更复杂的东西,比如
$text = preg_replace('/\s+/', ' ', 'word w.s');
$parts = explode(' ', $text, 2);
if (count($parts) < 2) {
throw new \RuntimeException('Should have more than two words');
}
foreach ($parts as $part) {
preg_match_all('/\w/u', $part, $matches);
if (count($matches[0]) < 2) {
throw new \RuntimeException('Should have more than two letters in word');
}
}
关于php - 检测字符串是否包含至少 2 个字母(任何语言)和至少 2 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11725927/