1

I am trying validate an array of strings to see if they are valid variable names, and if not throw an error. But using my test array (seen below), all keys come back as valid names, and I know that they shouldn't because the first one starts with a 3 which isn't valid. Am I doing something wrong?

foreach($key as $k => $v){
    if(!preg_match("'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'", $k)){
        throw new Exception("Invalid Meta Data Key Name");
    }
    $this->meta->$k = $v;
}

Regular Expression found here: http://php.net/manual/en/language.variables.basics.php

Here is the array that I am using to test the above:

$key = array(
    "3total"  => $this->foundRows,
    "rows"    => $this->resultSetSize,
    "page"    => $this->page,
    "pages"   => $this->getPages(),
    "offset"  => $this->getOffset(),
    "columns" => $this->columns,
)
2
  • 2
    You don't have ^$ anchors, so your expression matches anywhere inside the string. It isn't enforcing letters at the beginning. Single quotes ' are an unusual choice for regex delimiters, but I suppose if it's working for you... Something like / or ~ would be more conventional. Commented Mar 12, 2015 at 20:24
  • I figured it didn't need it since it wasn't in the expression in the manual. Commented Mar 12, 2015 at 20:25

1 Answer 1

3

That pattern is matching anywhere. You need to use the start of line anchor ^. End anchor $ may be needed for proper validation:

'^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$'
Sign up to request clarification or add additional context in comments.

1 Comment

The expression is showing the structure via an expression and is very common. It is not by itself a validation expression.

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.