Simple regex headaches

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
neridaj
Forum Commoner
Posts: 40
Joined: Fri Jan 05, 2007 9:55 pm

Simple regex headaches

Post 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
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Simple regex headaches

Post 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);
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Simple regex headaches

Post 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;
Post Reply