2012-11-04 29 views
-1

有行PHP正則表達式:檢查文本行的重複行

(01) Some text 
(10) Foo Bar 
(11) ? 
(13) Foo Bar 
(13) ? 
(20) Something else 

支票4行批處理。如果行1和3是相同的,行2和4是(XX) ?,然後用...替換行2-4所以它導致作爲

(01) Some text 
(10) Foo Bar 
... 
(20) Something else 

代碼:

$arr = explode("\n", $t); 
if (count($arr) > 3) { 
    for ($i=1; $i<count($arr); $i++) { // check 4 rows 
     if(($arr[$i-1] == $arr[$i+1]) // if row 1 and 3 are the same 
      && preg_match('/\(\d+\) \?$/', $arr[$i]) // and row 2 is "(XX) ?" 
     && preg_match('/\(\d+\) \?$/', $arr[$i+2]) // and row 4 is "(XX) ?" 
     ) { 
      print "Match!"; //test. later replace rows 2-4 with a row "..." 
     } 
    } 
} 

這目前給我一個抵消錯誤。

測試:http://codepad.viper-7.com/iMO3BW

這怎麼可能解決呢?

回答

0

使用正則表達式模式

^(\(\d+\)\s+)(.*)[\n\r]\(\d+\)\s+\?[\n\r]\(\d+\)\s+\2[\n\r]\(\d+\)\s+\?[\n\r] 

全球修飾。


this regex test

+0

哦,普通的正則表達式!沒有看到解決方案即將到來。謝謝! – Martin

0

您正在掃描最多兩個元素到未來,同時迭代到最後一個元素。你可以看到發生在這裏。

preg_match('/\(\d+\) \?$/', $arr[$i+2]) 

將您的FOR語句更改爲以下內容。

for($i=1; $i<count($arr) - 2; $i++) 
+0

-2?它也應該使用更多的行或正好4。 – Martin