dounouxi1020 2015-03-24 23:37
浏览 227
已采纳

如何使用preg_match只允许包含字母和数字字符的字符串?

I need a regex to accept only strings that contain both alphabetic and numeric characters. For example:

ABCDEF: wrong 
123456: wrong
!##$%@.: wrong
ABCD123!@$: wrong
ABC12389IKEIIJ29: **correct**

How can I do it with PHP?

  • 写回答

1条回答 默认 最新

  • dongshenling6585 2015-03-24 23:46
    关注
    preg_match('/^[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/', $subject);
    

    If you want to allow small and capital letters, add an i at the end of the pattern string.

    Explanation:

    [0-9][A-Z] matches one digit followed by one capital letter

    [A-Z][0-9] matches one capital letter followed by one digit

    ([0-9][A-Z]|[A-Z][0-9]) matches one of these two sequences

    [0-9A-Z]* matches 0-n digits and/or capital letters

    The idea is: A string which contains both (and only), letters and numbers, has at least one subsequence where a letter follows a digit or a digit follows a letter. All the other characters (preceding and following) have to be digits or letters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器