PHP glob具有不区分大小写的匹配 [英] PHP glob with case-insensitive matching
问题描述
我使用glob
查找文件夹为
$str = "Test Folder";
$folder = glob("$dir/*$str*");
如何告诉glob
进行匹配以找到不区分大小写的匹配文件夹?
How can I tell glob
to match to find the matching folders case-insensitive?
匹配 test文件夹, TEST FOLDER 等.
请注意,$str
是脚本的未知输入!
NOTE that $str
is an unknown input to the script!
推荐答案
我可以建议在$str
的每个字母上建立不区分大小写的字符范围吗?
May I suggest the build of case-insensitive character ranges on each letter of $str
?
代码:( 演示)
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]*
如果您需要多字节版本,这是我建议的代码段:(演示)
If you require a multibyte version, this is my suggested snippet: (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页面:
Related Stackoverflow page:
可以使用PHP的glob ()是否以不区分大小写的方式查找文件?
p.s.如果您不介意正则表达式的开销和/或更喜欢浓缩的单线,则将执行以下操作:(
p.s. If you don't mind the expense of regex and/or you prefer a condensed one-liner, this will do the same: (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]*
,这里是多字节版本:(演示)
and here is the multi-byte version: (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]*
这篇关于PHP glob具有不区分大小写的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!