简体   繁体   中英

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?

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 [^az] it means anything else than az.

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM