note 54519 deleted from function.glob by sobak
| From: | sobak@php.net | Date: | Thu, 01 Dec 2016 06:36:54 +0000 |
| Subject: | note 54519 deleted from function.glob by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207809@lists.php.net to get a copy of this message | ||
Note Submitter: x_terminat_or_3 at yahoo dot country:fr
----
This is a replacement for glob on servers that are running a php version < 4.3
It supports * and ? jokers, and stacking of parameters with ;
So you can do
<? $results=glob('/home/user/*.txt;*.doc') ?>
And it will return an array of matched files.
As is the behaviour of the built-in glob function, this one will also return boolean false if no
matches are found, and will use the current working directory if none is specified.
<?php
if(!(function_exists('glob')))
{function glob($pattern)
{#get pathname (everything up until the last / or \)
$path=$output=null;
if(PHP_OS=='WIN32')
$slash='\\';
else
$slash='/';
$lastpos=strrpos($pattern,$slash);
if(!($lastpos===false))
{$path=substr($pattern,0,-$lastpos-1); #negative length means take from the right
$pattern=substr($pattern,$lastpos);
}
else
{#no dir info, use current dir
$path=getcwd();
}
$handle=@ opendir($path);
if($handle===false)
return false;
while($dir=readdir($handle))
{if(pattern_match($pattern,$dir))
$output[]=$dir;
}
closedir($handle);
if(is_array($output))
return $output;
return false;
}
function pattern_match($pattern,$string)
{#basically prepare a regular expression
$out=null;
$chunks=explode(';',$pattern);
foreach($chunks as $pattern)
{$escape=array('$','^','.','{','}',
'(',')','[',']','|');
while(strpos($pattern,'**')!==false)
$pattern=str_replace('**','*',$pattern);
foreach($escape as $probe)
$pattern=str_replace($probe,"\\$probe",$pattern);
$pattern=str_replace('?*','*',
str_replace('*?','*',
str_replace('*',".*",
str_replace('?','.{1,1}',$pattern))));
$out[]=$pattern;
}
if(count($out)==1)
return(eregi("^$out[0]$",$string));
else
foreach($out as $tester)
if(eregi("^$tester$",$string))
return true;
return false;
}
}
?>
This function is case insensitive, but if needed, you can do this to make it behave depending on os:
* replace eregi in the example with my_regexp
add this function
<?php
function my_regexp($pattern,$probe)
{$sensitive=(PHP_OS!='WIN32');
$sensitive=false;
return ($sensitive?
ereg($pattern,$probe):
eregi($pattern,$probe));
}
?>