验证php中的classname

时间:2013-01-05 15:30:13

标签: php regex

  

可能重复:
  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;
     }
}

2 个答案:

答案 0 :(得分: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_') {
}

这些方式,读者可能会更快地阅读代码。与您正在使用的方法无关,请始终对该函数进行注释。

答案 1 :(得分:0)

替换它:

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

用这个:

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

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

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