php 字符串与通配符 * 匹配?
我想提供使用通配符 *
匹配字符串的可能性。
示例
$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
环境 *
匹配空
字符串)©vbence
有任何改进/建议吗?
// 添加了 return (bool)
因为 preg_match 返回 int
I want to give the possibility to match string with wildcard *
.
Example
$mystring = 'dir/folder1/file';
$pattern = 'dir/*/file';
stringMatchWithWildcard($mystring,$pattern); //> Returns true
Example 2:
$mystring = 'string bl#abla;y';
$pattern = 'string*y';
stringMatchWithWildcard($mystring,$pattern); //> Returns true
I thought something like:
function stringMatch($source,$pattern) {
$pattern = preg_quote($pattern,'/');
$pattern = str_replace( '\*' , '.*?', $pattern); //> This is the important replace
return (bool)preg_match( '/^' . $pattern . '$/i' , $source );
}
Basically replacing *
to .*?
(considering in *nix
environment *
matches empty
string) ©vbence
Any improvments/suggests?
// Added return (bool)
because preg_match returns int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这里不需要
preg_match
。 PHP 有一个通配符比较函数,专门针对这种情况:和
fnmatch('dir/*/file', 'dir/folder1/file ')
可能已经适合你了。但请注意*
通配符同样会添加更多斜杠,就像 preg_match 一样。There is no need for
preg_match
here. PHP has a wildcard comparison function, specifically made for such cases:And
fnmatch('dir/*/file', 'dir/folder1/file')
would likely already work for you. But beware that the*
wildcard would likewise add further slashes, like preg_match would.您应该只使用
.*
来代替。编辑:您的
^
和$
的顺序也错误。工作演示:http://www.ideone.com/mGqp2
You should just use
.*
instead.Edit: Also your
^
and$
were in the wrong order.Working demo: http://www.ideone.com/mGqp2
导致所有字符的非贪婪匹配。这不等于“*”,因为它不匹配空字符串。
以下模式也将匹配空字符串:
所以...
Causes non-greedy matching for all characters. This is NOT equal to "*" becuase it will not match the empty string.
The following pattern will match the empty string too:
so...
您混淆了结尾 (
$
) 和开头 (^
)。这:应该是:
You're mixing up ending (
$
) and beginning (^
). This:Should be:
您将遇到的一个问题是对
preg_quote()
的调用将转义星号字符。鉴于此,您的str_replace()
将替换*
,但不会替换其前面的转义字符。因此,您应该将
str_replace('*' ..)
更改为str_replace('\*'..)
The one problem you'll have is that the call to
preg_quote()
will escape the asterisk character. Given that, yourstr_replace()
will replace the*
, but not the escape character in front of it.Therefore you should change the
str_replace('*' ..)
withstr_replace('\*'..)