Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match pattern dosn't work in php v 5

i am using php version 5.4.45 . i test this code in php version 7 and work true but not work in version 5.4.45

$string = '9301234567';
if( preg_match('/^\9\d{9}/', $string) ) 
{
    $string = '0+1'.$string ;
    return $string ;
}

in v7 return :

0+19301234567

but in v5.4.45 return (preg_match return false)

9301234567

how i can use preg_match('/^\9\d{9}/', $string) in php v5.4.45 ? Thanks

like image 425
creavaehahea Avatar asked Jan 30 '23 00:01

creavaehahea


1 Answers

Brief

Your pattern is /^\9\d{9}/. Note that there's a \9 in there. This is usually interpreted as a backreference (which is what's happening in your earlier version of PHP). I guess the interpreter is now smarter and realizes your subpattern \9 doesn't exist and so it understands it as a literal 9 instead.

Edit - Research

I dug deeper into this change in behaviour and in PHP 5.5.10 they upgraded PCRE to version 8.34. Looking through the changelogs for PCRE, now, I discovered that version 8.34 of PCRE introduced the following change:

  1. Perl has changed its handling of \8 and \9. If there is no previously encountered capturing group of those numbers, they are treated as the literal characters 8 and 9 instead of a binary zero followed by the literals. PCRE now does the same.

Code

Use this regex instead.

/^9\d{9}/

Usage

See code in use here

<?php

$string = '9301234567';
if( preg_match('/^9\d{9}/', $string) ) 
{
    $string = '0+1'.$string ;
    print $string ;
}
like image 64
ctwheels Avatar answered Jan 31 '23 18:01

ctwheels