我正在使用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)
?谢谢
你的模式是/^\9\d{9}/
。请注意,那里有一个\9
。这通常被解释为反向引用(这是您早期版本的PHP中发生的事情)。我想解释器现在更聪明,并且意识到你的子模式\9
不存在,因此它将其理解为文字9
。
我在行为和PHP 5.5.10 they upgraded PCRE to version 8.34中深入研究了这种变化。现在,通过changelogs for PCRE,我发现PCRE版本8.34引入了以下更改:
- Perl已经改变了对\ 8和\ 9的处理。如果之前没有遇到这些数字的捕获组,则将它们视为文字字符8和9,而不是二进制零,后跟文字。 PCRE现在也是如此。
请改用此正则表达式。
/^9\d{9}/
<?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 ;
}