PHP regex: ^ and $ vs \A and \z

When tempted to do this:


$name = "joe";
if (preg_match('/^[a-zA-Z]+$/', $name) {
}


Chances are, you probably want use this instead:


if (preg_match('/\A[a-zA-Z]+\z/', $name) {
}


Why?

Use of ^ is OK, but $ matches line break characters.
So,


$name = "joe¥n";
if (preg_match('/^[a-zA-Z]+$/', $name) {
echo "match!";
}


Will display "match!" - which is probably something you don't want.
#php

People Who Wowed This Post

×
  • If you are a bloguru member, please login.
    Login
  • If you are not a bloguru member, you may request a free account here:
    Request Account