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

2022-08-30 13:08:37

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

$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 );
}

基本上替换到(考虑在环境中匹配字符串)©vbence*.*?*nix*empty

任何改进/建议?

之所以添加,是因为preg_match返回 intreturn (bool)


答案 1

这里没有必要。PHP有一个通配符比较功能,专门用于这种情况:preg_match

fnmatch()

而且可能已经为你工作了。但请注意,通配符同样会像preg_match一样添加更多斜杠。fnmatch('dir/*/file', 'dir/folder1/file')*


答案 2

您应该改用。.*

$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); 

工作演示:http://www.ideone.com/mGqp2


推荐