0

I'm using preg_match() to check if a user inputted string matches a required format. Previously, the local version of the website returned the same value as the production version, however, now the local version is returning False when it should be True.

Here's a sample of the code I'm using to validate a user's first name:

$firstName = 'John';
if (preg_match("/^[A-Z\p{L}][A-Z\' -\p{L}]{0,49}$/ui", $firstName)) {
echo 'True';
} else {
echo 'False';
}

The local version incorrectly returns False. In case it's relevant, it's running PHP version 5.5.17.

The production version correctly returns True. In case it's relevant, it's running PHP version 5.3.29.

I don't see any recent changes in the PHP spec for preg_match. Can anyone tell me why these 2 versions of the website return differing values when using the same code? Thank you.

9
  • Using v5.6.3 I get an error compiling the regex: invalid range in character class at offset 20
    – Tom Fenech
    Mar 5, 2015 at 14:14
  • I got the same result as @TomFenech Mar 5, 2015 at 14:17
  • 1
    These -\p seem to be the offending characters. You can do -\'p which will return TRUE. You may have forgotten a ' before the p - Or try [A-Z\-\p{L}] Mar 5, 2015 at 14:20
  • Related: stackoverflow.com/q/888838/2088135
    – Tom Fenech
    Mar 5, 2015 at 14:21
  • So, amidst the comments and an answer given; is this question still open? Mar 5, 2015 at 14:53

1 Answer 1

0

I also get the same result as @TomFenech, however if I remove the - before the 2nd "p". "/^[A-Z\p{L}][A-Z\' \p{L}]{0,49}$/ui", $firstName it responds with True

$firstName = 'John';
if (preg_match("/^[A-Z\p{L}][A-Z\' \p{L}]{0,49}$/ui", $firstName)) {
    echo 'True';
} else {
    echo 'False';
}

However, I also escaped the dash and also got True.

if (preg_match("/^[A-Z\p{L}][A-Z\' \-\p{L}]{0,49}$/ui", $firstName)) {

$ php -v
PHP 5.5.19 (cli) (built: Nov 14 2014 01:09:01)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
3
  • Thank you Adam, I think the second part of your answer looks like the solution I need, as it retains the existing regex format but with the desired validation outcome. I will test this and get back to you shortly. Mar 5, 2015 at 15:29
  • Cool. Hope it helped :)
    – Adam T
    Mar 5, 2015 at 17:42
  • It did, I've since tested this and this solution resolves the issue exactly as hoped, thanks again! Mar 5, 2015 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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