我正在努力使用PHP的一些正则表达式的东西。
我想实现什么
- 我想遍历某个位置的所有文件
- 如果文件是一个sql文件(由扩展名。sql标识)我想打开它,并找到所有abc@xyz匹配使用regex
我目前取得的成绩
- 遍历所有目录
- 与regex做一些匹配,但只有@xyz部分
我想要一些帮助
- 我怎么能改变我的正则表达式存储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_posn";
$result=preg_match("{bw*@w*b}",$file,$matches,PREG_OFFSET_CAPTURE,$at_pos);
print_r($matches);
}
}
} else {
echo "We could not open $namen";
}
}
}
?>
示例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;
在我看来,同时使用regex和解析是一个非常糟糕的主意。你可以用preg_match_all
代替。
if (strpos($file,'@') > 0) {
# we found at least one @ sign, now find all matches
preg_match_all('/b([a-zA-Z_0-9]+@[a-zA-Z_0-9]+)b/', $file, $matches)
}
结果现在在一个名为$matches的数组中,只需遍历它以查看所有匹配。
有关此函数的更多信息,请阅读文档:http://www.php.net/manual/en/function.preg-match-all.php