我正在使用 PHP 处理一些正则表达式的东西。
我想达到什么
- 我想遍历某个位置的所有文件
- 如果文件是 sql 文件(由扩展名 .sql 标识),我想打开它并使用正则表达式查找所有 abc@xyz 匹配项
我到目前为止所取得的成就
- 浏览所有目录
- 用正则表达式做一些匹配,但只有@xyz 部分
我需要什么帮助
- 如何更改我的正则表达式以在 $matches 数组中存储 abc@xyz 而不是 @xyz?
编码
<?php
$path = realpath('.');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
# go through each file/directory
foreach($objects as $name => $object){
#check if it is a sql file
if (strpos($name,'.sql') > 0) {
#open the file
$file = file_get_contents($name);
# check if the file could be succesfully read
if ($file) {
#if so we are looking for the @ sign identifying a db link
if (strpos($file,'@') > 0) {
# we found at least one @ sign, now go through the file again and again and again...
$at_pos=0;
while ($at_pos=strpos($file,'@',$at_pos+1)) {
echo "we got a db link in $name at position: $at_pos\n";
$result=preg_match("{\b\w*@\w*\b}",$file,$matches,PREG_OFFSET_CAPTURE,$at_pos);
print_r($matches);
}
}
} else {
echo "We could not open $name\n";
}
}
}
?>
示例 test2.sql 文件
-- thsis is a file with a db_link
select * from abc@db_link;
but look we also got Select * from ddks@db_link2;