Brian Adkins
Brian Adkins

Reputation: 666

passing preg_replace regex into a function

I'm using a function to read specific query string variables and strip them of non-desired characters,

The problem is that, when I try to use the passed-in regex class of '[^ -a-zA-Z0-9]' , the function does not strip anything out... However if I hard-code that same regex into the function, it works just fine.

Any ideas? Is there something inherently 'bad' about passing the desired regex class into a function?

Here is the function:

function CleanURLVariable($variablename,$defaultvalue,$allowedcharclass,$lowercase) {

    if (isset($_GET[$variablename])) {
            $temp = preg_replace('/'.$allowedcharclass.'/i','',urldecode(trim($_GET[$variablename])));

            if ($lowercase) {
                $value = strtolower($temp); 
            } else {
                $value = $temp;
            }
            return $value ;
        } else {
            return $defaultvalue;
        }
} // end of function CleanURLVariable

Called like this:

$myCleanedVariable = CleanURLVariable('kw',false,'[^ -a-zA-Z0-9]',false);

Upvotes: 0

Views: 204

Answers (1)

Czechnology
Czechnology

Reputation: 14992

Your regex is false, you need to place the hyphen at the beginning:

[^- a-zA-Z0-9]

Otherwise php is trying to create a range (space) to a.

$str = "sads#$!^!#adsd#gf\$dsgf";

echo preg_replace('/[^ -a-zA-Z0-9]/i','', $str) . PHP_EOL;
echo preg_replace('/[^- a-zA-Z0-9]/i','', $str) . PHP_EOL;

prints:

sads#$!^!#adsd#gf$dsgf

sadsadsdgfdsgf

Upvotes: 1

Related Questions