preg_match模式在php v5中不起作用

问题描述 投票:3回答:3

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

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

在v7返回:

0+19301234567

但是在v5.4.45中返回(preg_match返回false)

9301234567

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

php regex preg-match
3个回答
6
投票

简要

你的模式是/^\9\d{9}/。请注意,那里有一个\9。这通常被解释为反向引用(这是您早期版本的PHP中发生的事情)。我想解释器现在更聪明,并且意识到你的子模式\9不存在,因此它将其理解为文字9

Edit - Research

我在行为和PHP 5.5.10 they upgraded PCRE to version 8.34中深入研究了这种变化。现在,通过changelogs for PCRE,我发现PCRE版本8.34引入了以下更改:

  1. Perl已经改变了对\ 8和\ 9的处理。如果之前没有遇到这些数字的捕获组,则将它们视为文字字符8和9,而不是二进制零,后跟文字。 PCRE现在也是如此。

请改用此正则表达式。

/^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 ;
}

0
投票

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

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

在第一个\之前不需要9


0
投票

试试吧:

$string = '9301234567';
if( preg_match('/^[9]\d{9}/', $string) ) 
{
    $string = '0+1'.$string ;
    return $string ;
}
© www.soinside.com 2019 - 2024. All rights reserved.