Patartics Milán
Patartics Milán

Reputation: 4938

String filtering in php with preg_match and regular expression

I am creating a simple checker function in PHP to validate strings before putting them into an SQL query. But I can not get the right results the from the preg_match function.

$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
echo $tv;

Sometimes nothing echoed to the source code, not even a false value... I want to get 1 as the result of this call, because $myval only contains lowercase alphanumerics and numbers. So is there any way in php to detect if a string only contains lowercase alphanumerics and numbers using the preg_match function?

Upvotes: 2

Views: 4755

Answers (2)

tomsv
tomsv

Reputation: 7277

Yes, the circumflex goes outside the [] to indicate the start of the string, you probably need an asterisk to allow an arbitrary number of characters, and you probably want a $ at the end to indicate the end of the string:

$tv = preg_match('/^[a-z0-9]*$/', $myval);

If you write [^a-z] it means anything else than a-z.

Upvotes: 3

m.pons
m.pons

Reputation: 140

If you want to test if a string contains lowercase alphanumerics only, I would present your code that way to get the proper results (what you wrote already works):

$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
if($tv === 0){
    echo "the string only contains lowercase alphanumerics";
}else if($tv === 1){
    echo "the string does not only contain lowercase alphanumerics";
}else{
    echo "error";
}

Upvotes: 0

Related Questions