与通配符*匹配的php字符串?

与通配符*匹配的php字符串?,php,regex,string-matching,Php,Regex,String Matching,我想提供将字符串与通配符*匹配的可能性 范例 $mystring = 'dir/folder1/file'; $pattern = 'dir/*/file'; stringMatchWithWildcard($mystring,$pattern); //> Returns true 例2: $mystring = 'string bl#abla;y'; $pattern = 'string*y'; stringMatchWithWildcard($mystring,$patter

我想提供将字符串与通配符
*
匹配的可能性

范例

$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\u match返回int

您将遇到的一个问题是调用
preg\u quote()
将转义星号字符。因此,您的
str_replace()
将替换
*
,但不会替换前面的转义字符


因此,您应该将
str\u replace('*'..)更改为
str\u replace('\*'..)
您应该只使用
*

$pattern = str_replace( '*' , '.*', $pattern);   //> This is the important replace
编辑:您的
^
$
的顺序也不正确

<?php

function stringMatchWithWildcard($source,$pattern) {
    $pattern = preg_quote($pattern,'/');        
    $pattern = str_replace( '\*' , '.*', $pattern);   
    return preg_match( '/^' . $pattern . '$/i' , $source );
}

$mystring = 'dir/folder1/file';
$pattern = 'dir/*/file';

echo stringMatchWithWildcard($mystring,$pattern); 



$mystring = 'string bl#abla;y';
$pattern = 'string*y'; 

echo stringMatchWithWildcard($mystring,$pattern); 

导致所有字符的非贪婪匹配。这不等于“*”,因为它与空字符串不匹配

以下模式也将匹配空字符串:

.*?
所以

你把结尾(
$
)和开头(
^
)搞混了。这:

应该是:

preg_match( '/^' . $pattern . '$/i' , $source );

这里不需要
preg\u match
。PHP有一个通配符比较函数,专门针对以下情况:

而且
fnmatch('dir/*/file','dir/folder1/file')
可能已经适合您了。但是要注意,
*
通配符同样会添加更多的斜杠,就像preg\u match一样。

$pattern=str\u replace(“\*”,“.+?”,$pattern);//至少一个字符

我不知道我是否想让这个
'dir//file'
'dir/*/file'
*
匹配是贪婪的,它会吃掉字符串的所有剩余部分,而不仅仅是继续模式的最小字符数。因此,如果在
*
之后有任何内容,则结果将始终为false。根据您的描述,我认为这正是您想要对
+?
执行的操作。@vbence
preg_match('/.*a/','aa')
?好的,
match
将给出相同的结果。您认为我应该允许使用空字符串吗?也考虑DIR:<代码> 'dir//file < <代码>匹配<代码> 'dir/*/file ' >如果你想它类似于OS外壳如何工作,那么你必须允许空字符串。只需在windows中尝试
echo>hello
,然后在*nix中尝试
dir hello*
。在这个上下文中,*匹配空字符串。礼貌的做法是用-1.啊,很好!谢谢你的*尼克斯比较!(我也没有-1你的回答,我没有理由那样做)@123是的,我知道,没有指责。:)我从文件上漏掉了那件事。你好,马里奥。fnmatches还有一些其他功能,如
[]
。我只需要
*
,因为非POSIX系统不支持“特殊字符”fnmatch。(我看到php5.3+现在也支持windows)。因此,这并不总是最好的方法。请在代码中添加一些解释——看看这个问题的其他答案,以获得一些启示
stringMatchWithWildcard ("hello", "hel*lo"); // will give true
preg_match( '/$' . $pattern . '^/i' , $source );
preg_match( '/^' . $pattern . '$/i' , $source );