Page 1 of 1

Simple regex headaches

Posted: Thu Oct 16, 2008 3:47 pm
by neridaj
Hello,

I'm using a simple regex to validate property address so that they only contain alphanumeric and underscore characters. However, when I test the script on regexlib.com it works as expected, but when I run it from my script it does not. The script I'm using takes a property address (pa) from the query string and runs it through the regex for true or false. The validation script passes true for "120_Ho_St" but false for "120_Howe_St"? In fact, any instance of "Howe" in the query string returns false. It seems simple enough but I just don't understand, if you do I would appreciate any input.

Code: Select all

 
function valid_propadd($pa)
{
    if (ereg('(\w(\s)?)+', $pa))
        return true;
      else 
        return false;
}
 
    $pa = $_GET['pa'];
    if(!valid_propadd($pa))
                die("invalid property address!");
            else
    $propadd = $pa;
 
Thanks,

Jason

Re: Simple regex headaches

Posted: Thu Oct 16, 2008 4:25 pm
by GeertDD
I don't see exactly what goes wrong with your regex at first sight, but I'm not comfortable with ereg(). PCRE is generally preferred (e.i. preg_functions).

Code: Select all

function valid_propadd($pa)
{
    return (bool) preg_match('~^[a-z0-9_]++$~iD', $pa);
}

Re: Simple regex headaches

Posted: Sun Oct 19, 2008 4:30 am
by requinix
GeertDD wrote:I don't see exactly what goes wrong with your regex at first sight, but I'm not comfortable with ereg(). PCRE is generally preferred (e.i. preg_functions).
The ereg family of functions are being removed in PHP 6 I believe. Besides, PCRE is more powerful than POSIX anyways.

Here's something a bit simpler:

Code: Select all

return preg_match('/\W/', $pa) == 0;