ThomasJ
ThomasJ

Reputation: 69

Simple php preg_match not working for me

I have Googled and looked at a lot of threads on this subject but none answers this issue for me. I have even copied several different filter strings that do the same thing into do my simple validation. They all work on www.functions-online.com/preg_match.htm but none of them are working in my if() statement.

PHP ver. 5.3.3 My code to allow for only Alpha-Numaric and spaces:

  $myString = 'My Terrific Game';
  if (!preg_match('/^[a-z0-9\s]+$/i', $myString)) { "$errorMessage }

I have even reduced the filter to '/^[a-z]+$/' and the test string to 'mytarrificgame' and it still returns zero. It's as if preg_match() isn't functioning at all.

Anyone have any suggestions?

Upvotes: 4

Views: 15805

Answers (2)

ThomasJ
ThomasJ

Reputation: 69

I tried the filter string shown in the 2nd example of the first answer above and it didn't even work on the on-line test page but it did give me a new starting place to solve my dilemma. When I moved the carrot to before the opening bracket, it kind of works but flaky. After trying different things I finally got back to my original '/^[a-z0-9\s]+$\i' and it started working rock solid. I think the reason that it wouldn't work at all for me before is that I was expecting a boolean test on the preg-match() expression to accept a zero as false. This is probably a php version 5.3.3 thing. I tried the following;

  if(preg-match('/^[a-z0-9\s]+$/i', $testString) === 0) { "Do Something" }

It is now working. By looking deep into the preg-match() description, I found that it only returns a boolean false if an error occurred. A valid no-match returns a zero.

Thanks to all who looked here and considered my problem.

Upvotes: 0

Mariano
Mariano

Reputation: 6521

Some things you need to correct:

  • You have unclosed quotes in "$errorMessage. It should be $errorMessage or "$errorMessage".
  • There is no command there. If you want to print the value, use echo $errorMessage.
  • And is that variable being set anywhere in the code?

This should work

if (!preg_match('/^[a-z0-9\s]+$/i', $myString)) { echo $errorMessage; }

Or, if you think about it, matching only 1 character outside of those allowed should be enough.

Code:

$myString = 'My Terrific Game';
$errorMessage = 'ERROR: Unallowed character';

if (preg_match('/[^a-z0-9\s]/i', $myString)) { 
    echo $errorMessage;
} else {
    echo 'Valid input';
}

ideone Demo

Upvotes: 2

Related Questions