PHP正则表达式检查字符串是否是数字和字母,或者两者混合

2022-08-14  阅读 842 次

PHP正则表达式检查字符串是否是数字和字母,或者两者混合

<?php
   $strings = array('hello', 'foo!#$bar');
   foreach ($strings as $example) {
      if (ctype_alnum($example)) {
         echo "$example 由字母或数字组成。\n";
      }else {
         echo "$example 不全是字母或数字。\n";
      }
   }
?>

在标准C语言环境中,字母仅为[A-Za-z],该函数等效于preg_match('/^[a-z0-9]+$/iD',$text)

print_r(preg_match('/^[a-z0-9]{4,16}+$/iD',$text)); //限定4-----16个字符串
//.php正则判断是否同时有数字和字母
$subject = 'qq2';
print_r(preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)/', $subject));
//.如果要限定只能数字和字母的话, 限定下结尾
$subject = 'qq2';
print_r(preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]+$/', $subject));

$pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,20}$/';
if(!preg_match($pattern,$username)){
print_r('用户名只能是数字加字母组合');
}


本文地址:https://yaaibk.com/post/279.html
版权声明:本文为原创文章,版权归 本站 所有,欢迎分享本文,转载请保留出处!

评论已关闭!