php 字符串匹配通配符 *? [英] php string matching with wildcard *?

查看:61
本文介绍了php 字符串匹配通配符 *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to give the possibility to match string with wildcard *.

示例

$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

Basically replacing * to .*? (considering in *nix environment * matches empty string) ©vbence

任何改进/建议?

//添加了 return (bool) 因为 preg_match 返回 int

// Added return (bool) because preg_match returns int

推荐答案

这里不需要 preg_match.PHP 有一个通配符比较功能,专门针对这种情况:

There is no need for preg_match here. PHP has a wildcard comparison function, specifically made for such cases:

fnmatch()

而且 fnmatch('dir/*/file', 'dir/folder1/file') 可能已经对你有用了.但要注意 * 通配符同样会添加更多斜线,就像 preg_match 一样.

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.

这篇关于php 字符串匹配通配符 *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆