Preg匹配请求

时间:2014-12-02 20:31:16

标签: php regex preg-match

我需要一个正则表达式来查找字符串前缀是否为数字(_number)以及是否有获取此数字的

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

2 个答案:

答案 0 :(得分: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')将返回15testString('this_is_page15.html')将返回FALSE

答案 1 :(得分: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