【问题标题】:verify classname in php [duplicate]在php中验证类名[重复]
【发布时间】:2012-12-19 20:12:12
【问题描述】:

可能重复:
How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?
PHP: How to check if a string starts with a specified string?

我尝试编写自己的正则表达式,但我糟透了

#^(AJ\_)?.*#

问题是,我将创建一个这样的字符串:AJ______ClassNameBlahBlahBlah,我的函数返回 TRUE。我只需要AJ_ 和它后面的文字。

function isAnAJMClass($classname) {
     if (preg_match('#^(AJ\_)?.*#', $classname)) {
          return TRUE;
     } else {
         return FALSE;
     }
}

【问题讨论】:

  • 您指定了 .* 并且下划线是有效字符。您的规则是“以 AJ_ 开头,然后是任何内容”。你想要它是什么?
  • 我想要AJ_和AJ_之后的文字
  • 对你来说什么是“文本”?就像我说的,. 将匹配任何字符,所以“______fooBar”是“文本”。如果您只想要字母,请使用 [a-z]
  • 我正在寻找 1 个下划线

标签: php regex


【解决方案1】:

如果您确定字符串的开头总是有AJ_,您可以使用strpos($haystack, $needle) 而不是正则表达式。

function isAnAJMClass($classname) {
     if (strpos($classname, 'AJ_') === 0) {
          return TRUE;
     } else {
         return FALSE;
     }
}

也可以使用substr($str, $start, $len)

if (substr($classname, 0, 3) === 'AJ_') {
}

这些方式,读者大概可以更快地阅读代码。无论您使用的方法如何,请始终对函数进行注释。

【讨论】:

    【解决方案2】:

    替换这个:

    preg_match('#^(AJ\_)?.*#', $classname)
    

    用这个:

    preg_match('/^AJ_[a-zA-Z]+/', $classname)    
    

    这是您需要的正确正则表达式,它说:

    匹配以 AJ_ 开头的每个字符串,后跟小写或大写字母

    【讨论】:

    • 非常感谢。它运行顺利
    猜你喜欢
    • 2013-08-22
    • 2011-10-23
    • 1970-01-01
    • 2013-10-24
    • 2012-07-27
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多