简体   繁体   English

任何人都可以帮助我使用 PHP 中的正则表达式

[英]Can Anyone help me out with regular expression in PHP

I dont have much knowledge on Regular expression.我对正则表达式的了解不多。 Help me out if i could achieve the below, Username must need to validate this.如果我可以实现以下目标,请帮助我,用户名必须需要验证这一点。

  1. Only contains alphanumeric characters, underscore and dot仅包含字母数字字符、下划线和点
  2. Underscore and dot can't be at the end or start of a username下划线和点不能位于用户名的末尾或开头
  3. Underscore and dot can't be next to each other下划线和点不能相邻
  4. Underscore or dot can't be used multiple times in a row下划线或点不能连续多次使用

I have come up with this regular expression but i cant fulfill all the above.我想出了这个正则表达式,但我不能满足以上所有要求。

/(?<![a-z_|.])([a-z](?:[a-z]|_|.(?!_.))+[a-z]|[a-z]{2})(?![a-z_|.])/

Thanks in advance.提前致谢。

You don't need any lookbehind.你不需要任何回头看。 Simplify your regex to this:将您的正则表达式简化为:

/^[a-zA-Z0-9](?!(?:.*\.){2}|(?:.*_){2}|.*[._]{2})[a-zA-Z0-9_.]*[a-zA-Z0-9]$/

RegEx Demo正则表达式演示

One way to rome... (simple and easy version)去罗马的一种方式......(简单易行的版本)

if(substr_count($string,'_')<=1 //for rule 4.
    && substr_count($string,'.')<=1 //for rule 4.
    && substr_count($string,'._')===0 //for rule 3.
    && substr_count($string,'_.')===0 //for rule 3.
    && preg_match('/^[^_\.][a-zA-Z]+[^_\.]$/',$string)// for rule 1. & 2.
) {
     echo 'Valid';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM