【问题标题】:PHP glob with case-insensitive matching具有不区分大小写匹配的 PHP glob
【发布时间】:2017-07-16 15:18:18
【问题描述】:

我使用glob 来查找文件夹

$str = "Test Folder";
$folder = glob("$dir/*$str*");

我如何告诉glob 匹配以查找不区分大小写的匹配文件夹?

匹配测试文件夹测试文件夹

注意$str 是脚本的未知输入!

【问题讨论】:

  • 尝试[a-zA-Z]作为范围...
  • 你为什么要删除你的评论?
  • @VishalKumarSahu 这是模式的恒定部分。 $str 在这里是未知的。你如何用正则表达式模式定义它?
  • 你会从 GLOB 得到一个数组...在这个数组中你可以播放你想要的。

标签: php glob


【解决方案1】:

我可以建议在$str 的每个字母上构建不区分大小写的字符范围吗?

代码:(Demo)

function glob_i($string){  // this function is not multi-byte ready.
    $result='';  // init the output string to allow concatenation
    for($i=0,$len=strlen($string); $i<$len; ++$i){  // loop each character
        if(ctype_alpha($string[$i])){  // check if it is a letter
            $result.='['.lcfirst($string[$i]).ucfirst($string[$i]).']';  // add 2-character pattern
        }else{
            $result.=$string[$i];  // add non-letter character
        }
    }
    return $result;  // return the prepared string
}
$dir='public_html';
$str='Test Folder';

echo glob_i($str);  // [tT][eE][sS][tT] [fF][oO][lL][dD][eE][rR]
echo "\n";
echo "$dir/*",glob_i($str),'*';  // public_html/*[tT][eE][sS][tT] [fF][oO][lL][dD][eE][rR]*

如果您需要多字节版本,这是我建议的 sn-p:(Demo)

function glob_im($string,$encoding='utf8'){
    $result='';
    for($i=0,$len=mb_strlen($string); $i<$len; ++$i){
        $l=mb_strtolower(mb_substr($string,$i,1,$encoding));
        $u=mb_strtoupper(mb_substr($string,$i,1,$encoding));
        if($l!=$u){
            $result.="[{$l}{$u}]";
        }else{
            $result.=mb_substr($string,$i,1,$encoding);
        }
    }
    return $result;
}
$dir='public_html';
$str='testovací složku';

echo glob_im($str);  // [tT][eE][sS][tT][oO][vV][aA][cC][íÍ] [sS][lL][oO][žŽ][kK][uU]
echo "\n";
echo "$dir/*",glob_im($str),'*';  // public_html/*[tT][eE][sS][tT][oO][vV][aA][cC][íÍ] [sS][lL][oO][žŽ][kK][uU]*

相关的 Stackoverflow 页面:

Can PHP's glob() be made to find files in a case insensitive manner?


附言如果您不介意正则表达式的费用和/或您更喜欢精简的单行,这将做同样的事情:(Demo)

$dir='public_html';
$str='Test Folder';
echo "$dir/*",preg_replace_callback('/[a-z]/i',function($m){return '['.lcfirst($m[0]).ucfirst($m[0])."]";},$str),'*';  // $public_html/*[tT][eE][sS][tT] [fF][oO][lL][dD][eE][rR]*

这里是多字节版本:(Demo)

$encoding='utf8';
$dir='public_html';
$str='testovací složku';
echo "$dir/*",preg_replace_callback('/\pL/iu',function($m)use($encoding){return '['.mb_strtolower($m[0],$encoding).mb_strtoupper($m[0],$encoding)."]";},$str),'*';  // public_html/*[tT][eE][sS][tT][oO][vV][aA][cC][íÍ] [sS][lL][oO][žŽ][kK][uU]*

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多