0

PHPを使用していくつかの正規表現に苦労しています。

達成したいこと

  • 特定の場所にあるすべてのファイルを繰り返し処理したい
  • ファイルが sql ファイル (拡張子 .sql で識別される) である場合、それを開いて、正規表現を使用してすべての abc@xyz 一致を見つけたい

これまでに達成したこと

  • すべてのディレクトリを通過する
  • 正規表現とのマッチングを行いますが、@xyz 部分のみです

助けてほしいこと

  • $matches 配列に @xyz の代わりに abc@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;
4

1 に答える 1

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)

}

結果は name $matches の配列になりました。すべての一致を表示するには、それを反復処理するだけです。

この関数の詳細については、次のドキュメントを参照してください: http://www.php.net/manual/en/function.preg-match-all.php

于 2013-05-08T20:06:24.083 に答える