0

Running Linux (Ubuntu 11.10), the same regular expression works in JavaScript, but fails when & is included in the string being evaluated in PHP. Here's what I mean:

JavaScript regex:

regex = /^(?:[a-zA-Z0-9 ',.@&!+-]{3,50})$/;

PHP regex:

$settings['regex_name'] = "/^(?:[a-zA-Z0-9 ',.@&!+-]{3,50})$/";

When the code runs in a browser to verify a string (for example D & L Auto Sales), JavaScript matches the entire string as it should. However, when the server-side code attempts to match on the same string, it fails.

Has anyone run into this before?

EDIT: This is the PHP code that runs the regex:

function validated_array(&$array) {
    global $settings;

    $filterDefinitions = array( "name" => array('filter' => FILTER_VALIDATE_REGEXP,
                                'options' => array('regexp' => $settings['regex_name']),
        ...
    );


    $retVal = filter_var_array($array, $filterDefinitions);

When the code runs with D & L Auto Sales, $retVal['name'] is empty. However, when I remove the &, $retVal['name'] has a value.

4
  • 2
    As a general rule you can't assume that regular expressions will work identically in every scripting/programming language. In your case, I'm assuming there are different escape character requirements. Commented Feb 21, 2012 at 0:13
  • 7
    Works for me using preg_match(). How are you executing the regex match? Commented Feb 21, 2012 at 0:13
  • I've added the PHP code above. Commented Feb 21, 2012 at 1:02
  • Not sure why this was down voted? Would it have helped if I had linked to us3.php.net/manual/en/regexp.reference.meta.php? Commented Feb 21, 2012 at 1:14

1 Answer 1

2

Are you sure the & is not encoded as & in your HTML ?

Otherwise, Perl Compatible Regular Expressions have a high rate of compatibility between JavaScript and PHP (supported by both), and especially the one you gave in your example.

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

2 Comments

This is close enough to the problem: "name" comes from the URL, and it is decoded (turning & into &) for use in most of the javascript, so when I reuse the value in an ajax query, the & truncates the name short enough to fail validation. Thanks!
@JoBu1324 No worries. Glad you figured it out.

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.