Reputation: 69
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
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
Reputation: 6521
Some things you need to correct:
"$errorMessage
. It should be $errorMessage
or "$errorMessage"
.echo $errorMessage
.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';
}
Upvotes: 2