0

I used this regex in the JavaScript for my webpage, and it worked perfectly:

var nameRegex = /^([ \u00c0-\u01ffa-zA-Z'\-])+$/;
return nameRegex.test(name);

I then wanted to include it in my PHP script as a second barrier in case the user disables JavaScript etc. But whenever I use it it will fail every string that I pass through it, even correct names. I tried using single quotes to stop escape characters, but then I had to escape the single quote contained within the regex, and came up with this:

$nameRegex = '/^([ \u00c0-\u01ffa-zA-Z\'\-])+$/';
if ($firstName == ""){
    $valSuccess = FALSE;
    $errorMsgTxt .= "Please enter your first name<br>\n";
} elseif (!preg_match($nameRegex, $firstName)){
    $valSuccess = FALSE;
    $errorMsgTxt .= "Please enter a valid first name<br>\n";
}

But, once again, it fails valid names.

So my question is, how can I make my regex "safe" for use in PHP?

5
  • have you tried making your regexp unicode-friendly with the u modifier ? '/^([ \u00c0-\u01ffa-zA-Z\'\-])+$/u'; Commented Dec 21, 2013 at 15:15
  • @Calimero Thanks for the suggestion, but still doesn't work Commented Dec 21, 2013 at 15:20
  • @user2180613 still no joy I'm afraid Commented Dec 21, 2013 at 15:49
  • Have you tried removing the initial and final forward slashes? Commented Dec 21, 2013 at 15:58
  • @JackNewcombe still fails Commented Dec 21, 2013 at 16:10

1 Answer 1

2

The problem with your regular expression is that this works in , but your syntax is not valid in .

You need to consider \X which matches a single Unicode grapheme, whether encoded as a single code point or multiple code points using combining marks. The correct syntax would be..

/^[ \X{00c0-01ff}a-zA-Z'-]+$/
Sign up to request clarification or add additional context in comments.

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.