2013-05-08 99 views
0

我正在努力使用PHP的一些正則表達式的東西。在PHP正則表達式找到abc @ xyz不能按預期工作

什麼我想實現

  • 我想通過所有文件在某個位置
  • 迭代如果該文件是一個SQL文件(擴展名.sql標識)我想打開它,找到所有ABC @某某使用正則表達式

我取得了什麼至今

匹配
  • 經過的所有目錄
  • 做一些匹配與正則表達式,但只有@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 [email protected]_link; 

but look we also got Select * from [email protected]_link2; 

回答

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][email protected][a-zA-Z_0-9]+)\b/', $file, $matches) 

} 

結果現在在一個名爲$ matches的數組中,只是遍歷它來查看所有匹配。

想了解更多關於此功能,閱讀文檔:http://www.php.net/manual/en/function.preg-match-all.php

+0

感謝你知道爲什麼我得到的兩次比賽中我的$匹配陣列? 陣列 ( [0] =>數組 ( [0] => ABC @ db_link [1] =>的DDK @ db_link2 ) [1] =>數組 ( [0] => ABC @db_link [1] => ddks @ db_link2 ) ) – 2013-05-08 20:16:36

+0

忘記我的最後一條評論.....典型的RTFM情況..謝謝 – 2013-05-08 20:19:38

+0

好吧,我坐在火車上,所以我有點兒並擺脫了體面的數據漫遊。真高興你做到了。我將通過指向未來觀衆的文檔的鏈接對其進行編輯。 – melwil 2013-05-08 20:22:43

相關問題