2014-12-02 105 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