[thelist] [php] regexp help

Edwin Martin edwin at bitstorm.org
Tue Oct 19 05:14:50 CDT 2004


Paul Bennett wrote:

> one day I'm going to buy that OReilly book, but until then:
>
> Can someone tell me why this check:
>
> if(preg_match("/^[a-zA-Z0-9 -\']+$/i", $value))
>   {$response['name'] = true;}
>       else {$response['name'] = false;}
>
> evaluates to true when $value is something like 'test ^%' - which 
> should return false?

A dollar-sign in a quoted string is used for variable substitution.

So, when $a is "john", the string "hello $a" would become "hello john".

Since in $/i there is no variable name after $, the $ is substituted 
with nothing.

When you want to keep the dollar, you have to escape it: \$.

So the code would become:

if (preg_match("/^[a-zA-Z0-9 -\']+\$/i", $value)) {
    $response['name'] = true;
} else {
    $response['name'] = false;
}

(I rewrote the code to make it more readable to other programmers.)

Edwin Martin

-- 
http://www.bitstorm.org/edwin/en/



More information about the thelist mailing list