|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-02-25 18:56 UTC] fabriziodimeo at alice dot it
Description:
------------
preg_match do not match correctly.
Reproduce code:
---------------
<?php
function anti_injection($stringa) {
$pattern="/[A-Za-z0-9]/";
if (preg_match($pattern, $stringa)) {
echo "ok"; }
else {
echo "hacking";
}
}
$str="c";
anti_injection($str);
$str="ciao!";
anti_injection($str);
?>
Expected result:
----------------
ok
hacking
Actual result:
--------------
ok
ok
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 14:00:01 2025 UTC |
I tested the two functions (preg_match and ereg) and this is the result: <?php function test($str) { if (preg_match("/[a-zA-Z0-9]+/",$str)) { echo "it's ok<BR>"; } else { echo "not ok<BR>"; } } function test2($str) { if (ereg("^[a-zA-Z0-9]+$",$str)) { echo "it's ok<BR>"; } else { echo "not ok<BR>"; } } echo "PREG_MATCH<BR><BR>"; test("iao"); test("$iao"); test("iao!"); test("123!"); test("123"); echo "<BR>"; echo "EREG<BR><BR>"; test2("iao"); test2("$iao"); test2("iao!"); test2("123!"); test2("123"); ?> The result is: PREG_MATCH not ok not ok not ok not ok not ok EREG it's ok not ok not ok not ok it's okThere is no bug here. The first example just looks for any character anywhere in the string. You would need to change it to: $pattern="/^[A-Za-z0-9]$/"; to get the result you want. Same goes for the second example. Your ereg and preg regular expressions are not the same. Your preg one is not anchored the same way your ereg one is. Make it the same and you get the same results: if (preg_match("/^[a-zA-Z0-9]+$/",$str))