0

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);

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think you nailed it... I think I added the space and the dash as 'acceptable' characters at different times and didn't pay attention to the order... When I was testing the hard-coded version, I typed in the REGEX correctly instead of copy-paste... thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.