PHP中的正则表达式找到abc @ xyz没有按预期工作

时间:2013-05-08 19:51:07

标签: php regex

我正在努力使用PHP的一些正则表达式。

我想要实现什么

  • 我想迭代某个位置的所有文件
  • 如果文件是sql文件(由扩展名.sql标识)我想打开它并使用regex查找所有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;

1 个答案:

答案 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