2014-12-02 76 views
0

我需要一个正则表达式查找字符串是否前缀号码(_number),如果没有得到这个数字的Preg匹配要求

//Valid 

if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page_15.html')) 
{ 
    $page = 15; 
} 

//Invalid 

if (preg_match('/^([a-zA-Z0-9_])+([_])+([0-9]).html$/i', 'this_is_page15.html')) // return false; 
+0

为什么你觉得regex是这里最好的解决方案?你基本上只对在最后一个'_'之后得到字符串部分感兴趣。这对于简单的字符串操作很简单(即'strrpos()'和类似的)。 – 2014-12-02 21:34:23

回答

1

如果我正确认识你,你可能需要某种功能来做到这一点。如果发现匹配,preg_match将返回1,如果找不到匹配则返回0,如果发生错误则返回FALSE。您需要提供第三个参数$matches来捕获匹配的字符串(详情请见:http://php.net/manual/en/function.preg-match.php)。

function testString($string) { 
    if (preg_match("/^\w+_(\d+)\.html/",$string,$matches)){ 
     return $matches[1]; 
    } else { 
     return false; 
    } 
} 

所以testString('this_is_page_15.html')将返回15,并testString('this_is_page15.html')将返回FALSE

0
$str = 'this_is_page_15.html'; 
$page; 
if(preg_match('!_\d+!', $str, $match)){ 
    $page = ltrim($match[0], "_"); 
}else{ 
    $page = null; 
} 
echo $page; 
//output = 15