3
我有一个我写的python脚本,我需要移植到php。它递归地搜索给定的目录并基于正则表达式搜索建立一个字符串。下面是我尝试移植的第一个函数。它需要一个正则表达式和一个基本目录,递归搜索该目录中的所有文件以获取正则表达式,并构建一个字符串匹配列表。从Python到PHP的GREP功能
def grep(regex, base_dir):
matches = list()
for path, dirs, files in os.walk(base_dir):
for filename in files:
fullpath = os.path.join(path, filename)
with open(fullpath, 'r') as f:
content = f.read()
matches = matches + re.findall(regex, content)
return matches
我从来不使用PHP,除了基本的GET参数操作。由于我完全缺乏php API,我从网上抓取了一些目录行走代码,并且努力使它像上面的python函数一样工作。
function findFiles($dir = '.', $pattern = '/./'){
$prefix = $dir . '/';
$dir = dir($dir);
while (false !== ($file = $dir->read())){
if ($file === '.' || $file === '..') continue;
$file = $prefix . $file;
if (is_dir($file)) findFiles($file, $pattern);
if (preg_match($pattern, $file)){
echo $file . "\n";
}
}
}
为什么不简单地在cli上使用grep? 'grep -d递归'你的字符串'? –
看看[glob()](http://us2.php.net/manual/en/function.glob.php) –
我点击这个PHP脚本通过一个http请求,并需要返回的值在一定格式,所以常规的grep将不起作用。将检查出glob()=。 – bitpshr