By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

preg_match always returning true

Why preg_match might return true, when you expect it to return false.

Created: 2012-02-25 17:36

If preg_match doesn't work, or for some reason returns true unexpected, you might just need to include the start and end metacharacters in the pattern. The caret "^" is used to indicate the beginning of a string, while the dollar sign "$" indicates the end of a string.

The below example would match the characters a-z anywhere in the string, and still allow the presence of other characters, but only when a-z are present somewhere in the string.

if (preg_match("/[a-z]+/", $_POST['name'])) {
   echo 'Valid: '.$_POST['name'];exit();

This is a trap if you don't test your code properly, and could open up a box of potential security issues. The next example will include the start and end metacharacters.

if (preg_match("/^[a-z]+$/", $_POST['name'])) {
   echo 'Valid: '.$_POST['name'];exit();

This pattern would only allow the characters a-z to exist in the string.