我正在努力使用PHP的一些正则表达式。
我想要实现什么
到目前为止我取得的成就
我想要一些帮助
代码
<?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;
答案 0 :(得分:0)
使用正则表达式和解析一起让我觉得非常糟糕。您可以改为使用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