preg_match 模式在 php v 5 中不起作用

preg_match pattern dosn't work in php v 5

我正在使用 php 版本 5.4.45。 我在 php 版本 7 中测试了此代码并且工作正常但在版本 5.4.45

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

在 v7 return 中:

0+19301234567

但在 v5.4.45 中 return(preg_match return false)

9301234567

如何在 php v5.4.45 中使用 preg_match('/^\d{9}/', $string)? 谢谢

简介

你的模式是/^\d{9}/。请注意,那里有一个 </code>。这通常被解释为反向引用(这是您早期版本 PHP 中发生的情况)。我想解释器现在更聪明了,它意识到你的子模式 <code> 不存在,所以它把它理解为文字 9 而不是。

编辑 - 研究

我深入研究了这一行为变化,在 PHP 5.5.10 they upgraded PCRE to version 8.34. Looking through the changelogs for PCRE 中,现在,我发现 PCRE 8.34 版引入了以下变化:

  1. Perl has changed its handling of and . 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.

代码

改用这个正则表达式。

/^9\d{9}/

用法

See code in use here

<?php

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

在 php 5.34 和 php 7.01 中进行了测试:

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

不需要第一个9

之前的\

试一试:

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