【发布时间】:2011-09-04 00:26:28
【问题描述】:
我想提供用通配符*匹配字符串的可能性。
例子
$mystring = 'dir/folder1/file';
$pattern = 'dir/*/file';
stringMatchWithWildcard($mystring,$pattern); //> Returns true
示例 2:
$mystring = 'string bl#abla;y';
$pattern = 'string*y';
stringMatchWithWildcard($mystring,$pattern); //> Returns true
我的想法是这样的:
function stringMatch($source,$pattern) {
$pattern = preg_quote($pattern,'/');
$pattern = str_replace( '\*' , '.*?', $pattern); //> This is the important replace
return (bool)preg_match( '/^' . $pattern . '$/i' , $source );
}
基本上将* 替换为.*?(考虑在*nix 环境中* 匹配empty 字符串)©vbence
有什么改进/建议吗?
// 添加 return (bool) 因为 preg_match 返回 int
【问题讨论】:
标签: php regex string-matching