2017-02-25 114 views
4

PHP水珠我用glob查找文件夾,不區分大小寫的匹配

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

我怎麼能告訴glob匹配找到相應的文件夾不區分大小寫?

匹配test文件夾test文件夾

注意的是$str是一個未知的輸入腳本!

+0

可能出現[可以使用PHP的glob()以不區分大小寫的方式查找文件的副本?](http://stackoverflow.com/questions/2520612/can-phps-glob-be-made-to -ind-files-in-a-case-insensitive-manner) –

+0

嘗試'[a-zA-Z]'作爲範圍... –

+0

你爲什麼要刪除你的評論? –

回答

3

我可以建議在每個字母$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]* 

如果你需要一個多字節版本,這是我的建議的片段:(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]* 

相關#1頁:

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


p.s.如果你不介意的正則表達式的費用和/或你喜歡一個濃縮的一行,這也將這樣做:()

$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]* 
相關問題