1

Problem:-

I am using the following regex to find the special characters in a string

"/[^a-zA-Z0-9\s]/i"

I want to get all the characters that match this pattern and all that is working fine.

The condition is that that I have to use the same expression both in php and javascript.

But the g flag in the above regex is creating problem as preg_match and preg_match_all do not accept this flag and I have to search globally.

Question:-

SO how can I get all the special characters using the same expression both in php and javascript?

2
  • How are you getting the regex in both places, and why can't it be edited for JS? Commented Jan 25, 2015 at 12:51
  • The regex could be modified in php to use it in javascript. But I am asking if there is any better idea of achieving that?? Commented Jan 25, 2015 at 12:52

2 Answers 2

1

You can't use the same regex in both PHP and JavaScript because their regex engines make different assumptions and support different features.

More than just the incompatibility with the g modifier, this regex will fail you if the input contains non-ASCII characters: the input encoding in PHP and JS will be almost certainly different and PHP will not even be Unicode-aware unless you use the u flag (which does not exist in JS because it's Unicode-aware by default).

Just use two different regular expressions.

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

Comments

0

To match [^a-zA-Z0-9\s] in JavaScript you would have to use:

[\u0000-\u0008\u000F-\u001F\u0022-\u002F\u003B-\u0040\u005C-\u0060\u007C-\u0084\u0087-\u009F\u00A2-\u167F\u1682-\u180D\u1810-\u1FFF\u200C-\u2027\u202B-\u202E\u2031-\u205E\u2061-\u2FFF\u3002-\uFFFF]

Comments

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.