我想要一个正则表达式来表示文本,如果里面有至少2个字母的1个单词,则允许它,并且最少25个字母或数字,如果那里有其他字母或数字,则还允许(0-9äöü,.--) ,应该给出一个错误。
示例:
正确:
false:
正则表达式:
if(preg_match("/([A-Za-z]{2})\w+/",$text)){
if(!preg_match("/[a-zäöüA-ZÄÖÜ,.' -]/g",$text)){echo 'error';}
else{echo'error';}
我不确定如何在代码中获得解决方案。
答案 0 :(得分:8)
您可能要做的是使用正向前瞻来断言长度为25-999,并断言有两个连续的[a-z]
然后将您的角色类[a-zA-Z0-9äöü,.' -]+
与允许添加a-z和A-Z的项相匹配。
^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$
^
字符串的开头(?=.{25,999})
正向查找,断言25-99个字符(?=.*[a-z]{2})
正向前进,断言2次[a-z] [a-zA-Z0-9äöü,.' -]+
匹配列出的1次以上任何时间$
字符串结尾例如(我将字符串变长了,以使其最小长度为25)
$strings = [
"This is a text with John Doe",
"This is a text with Max Müstermann ",
"This is a text withJohn-Frank' Doe.",
"This is a text with John/Doejlkjkjlk",
];
$pattern = "/^(?=.{25,999})(?=.*[a-z]{2})[a-zA-Z0-9äöü,.' -]+$/";
foreach ($strings as $string) {
if (preg_match($pattern, $string)) {
echo "Ok ==> $string" . PHP_EOL;
} else {
echo "error" . PHP_EOL;
}
}
结果
Ok ==> This is a text with John Doe
Ok ==> This is a text with Max Müstermann
Ok ==> This is a text withJohn-Frank' Doe.
error