Php 预匹配请求
我需要一个正则表达式来确定字符串前缀是否指向数字(_number),以及是否有必要获取这个数字Php 预匹配请求,php,regex,preg-match,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'))
//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;
如果我理解正确的话,您可能需要某种函数来实现这一点
preg_match
如果找到匹配项,将返回1
;如果未找到匹配项,将返回0
;如果出现错误,将返回FALSE
。您需要提供第三个参数$matches
,以捕获匹配的字符串(详细信息如下:)
所以
testString('this_is_page_15.html')
将返回15
,而testString('this_is_page15.html')
将返回FALSE
为什么您认为regex是这里最好的解决方案?基本上,您只对获取最后一个\uu
之后的字符串部分感兴趣。使用简单的字符串操作(即strrpos()
和类似操作)可以很容易地做到这一点。
$str = 'this_is_page_15.html';
$page;
if(preg_match('!_\d+!', $str, $match)){
$page = ltrim($match[0], "_");
}else{
$page = null;
}
echo $page;
//output = 15
function testString($string) {
if (preg_match("/^\w+_(\d+)\.html/",$string,$matches)){
return $matches[1];
} else {
return false;
}
}