【问题标题】:Regex in PHP to find abc@xyz not working as expectedPHP 中的正则表达式查找 abc@xyz 未按预期工作
【发布时间】:2013-05-09 04:23:23
【问题描述】:

我在使用 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;

【问题讨论】:

    标签: php regex


    【解决方案1】:

    同时使用正则表达式和解析让我觉得这是一个非常糟糕的主意。你可以改用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

    【讨论】:

    • 谢谢你知道为什么我在 $matches 数组中得到了两次匹配吗?数组 ( [0] => 数组 ( [0] => abc@db_link [1] => ddks@db_link2 ) [1] => 数组 ( [0] => abc@db_link [1] => ddks@db_link2 ) )
    • 好吧,我正坐在火车上,所以我有点进进出出像样的数据漫游。真高兴你做到了。我将编辑它并为未来的观众提供指向文档的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2021-07-16
    • 2022-01-02
    相关资源
    最近更新 更多