php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51148 preg_match doesn't work...le't post an example
Submitted: 2010-02-25 18:56 UTC Modified: 2010-02-25 20:02 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: fabriziodimeo at alice dot it Assigned:
Status: Not a bug Package: *Regular Expressions
PHP Version: 5.3.1 OS: windows and linux
Private report: No CVE-ID: None
 [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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-02-25 19:14 UTC] alessandro dot romani at vivanet dot it
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 ok
 [2010-02-25 20:02 UTC] rasmus@php.net
There 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))
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 15:01:29 2024 UTC