vote up 2 vote down star

After my webform is submitted, regex will be applied to user input on the server side (via PHP). I'd like to have the identical regex running in real-time on the client side to show the user what the real input will be. This will be pretty much the same as the Preview section on the Ask Question pages on StackOverflow except with PHP on the back-end instead of .NET.

What do I need to keep in mind in order to have my PHP and JavaScript regular expressions act exactly the same as each other?

flag

5 Answers

vote up 4 vote down check

Hehe this was sort of asked moments ago and Jeff pointed out:
http://www.regular-expressions.info/refflavors.html.

There is a comparison of regular expression capabilities across tools and languages.

link|flag
vote up 3 vote down

@LKM AJAX is the clear winner here. This will also allow you to follow the DRY principle. Why would you want to write your parsing code in Javascript and PHP?

link|flag
vote up 2 vote down

If the regular expressions are simple then there should be no issue, as the basics of regular expressions are common across most implementations.

For particulars then it would be best to study both implementations:

http://www.regular-expressions.info/php.html

http://www.regular-expressions.info/javascript.html

Javascripts implementation is probably the more basic, so if you are going for a lowest common denominator approach then aim for that one.

link|flag
vote up 1 vote down

I've found that different implementations of regular expressions often have subtle differences in what exactly they support. If you want to be entirely sure that the result will be the same in both frontend and backend, the savest choice would be to make an Ajax call to your PHP backend and use the same piece of PHP code for both regex evaluations.

link|flag
vote up 0 vote down

Both JavaScript's regex and PHP's preg_match are based on Perl, so there shouldn't be any porting problems. Do note, however, that Javascript only supports a subset of modifiers that Perl supports.

For more info for comparing the two:

As for delivery method, I'd suggest you'd use JSON, the slimmest data interchange format as of date (AFAIK) and directly translatable to a JavaScript object through eval(). Just put that bad boy through an AJAX session and you should be set to go.

I hope this helps :)

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.