0

Possible Duplicate:
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?

I tried writing my own regex, but I suck at it.

#^(AJ\_)?.*#

The problem is, I will make a string like so: AJ______ClassNameBlahBlahBlah and my function returns TRUE. All I need is just AJ_ and text after it.

function isAnAJMClass($classname) {
     if (preg_match('#^(AJ\_)?.*#', $classname)) {
          return TRUE;
     } else {
         return FALSE;
     }
}
Community
  • 1
  • 1
NONE
  • 471
  • 1
  • 4
  • 9

2 Answers2

1

If you're sure that there will be always AJ_ at the start of the string, you can use strpos($haystack, $needle) instead of regular expressions.

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

The use of substr($str, $start, $len) is also possible

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

These ways, the reader can probably read the code more quickly. Independently of the method you're using, always comment the function.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
0

Replace this:

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

with this:

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

Here is the right regular expression you need and it says:

Match every string that starts with: AJ_ followed by letters that are lowercase or uppercase