2011-05-21 77 views
0

我對正則表達式有一個非常基本的問題。我想匹配,更換網址,像這樣的:簡單正則表達式中同一行上有多個匹配的問題

http://mydomain.com/image/13/imagetitle.html 

對於我用下面的表達式:

/mydomain.com(.*)image\/(\d+)\/(.*).html/ 

這種模式工作正常居多,但它並不時出現多次出現在工作同一條線。所以這個工程:

This is my own image: http://mydomain.com/image/13/imagetitle.html 

當包括跨線多次出現它的工作原理,以及:

This is my own image: http://mydomain.com/image/13/imagetitle.html 
Yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 

兩次出現匹配,並且正確地更換。然而,這只是取代了第一場比賽的時候有兩次出現在同一行:

This is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 

我怎樣才能確保所有比賽被替換,無論新線?

+1

你可以粘貼你用來做替換的代碼嗎? – VladFr 2011-05-21 12:19:18

+0

實際上,從preg_replace()函數的角度來看,<不是換行符。這兩個例子都被視爲單行主題。如果你顯示你的替換代碼,它會更清晰。 – Kel 2011-05-21 12:35:33

+0

@凱爾:我很確定實際文本在那個地方有一個換行符,但是操作系統把它改成了'
',因爲他錯誤地認爲換行符在發佈問題時會被規範化到一個空間。正如你指出的那樣,如果真的有'
'那裏,他不會有這個問題。 – 2011-05-21 19:03:43

回答

2

我也沒有得到任何問題。但從正則表達式來看,你的問題很可能是貪婪。

(.*)儘可能匹配。如果它們位於同一行,它將一次捕獲兩個URL。因此,您通常希望使用(.*?),或應用標準/U

但在你的情況我建議乾脆讓比賽更加具體:

/mydomain.com(\S*)image\/(\d+)\/(\S*).html/ 

這裏\S將只匹配任何不是空格,因爲這是最肯定是其中的URL應該被打破了。作爲替代方案,您可以使用更具體的字符類,如([\w/.?&#%=-]*)而不是.*?

+0

謝謝,完美的作品!這確實是一個貪婪問題,我完全按照你的建議使用了「特定匹配」完整規則。 – Ferdy 2011-05-21 13:08:50

0

您的模式正在工作。我已經通過foll代碼對其進行了測試:

$data = "This1 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 
This2 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 
This3 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 
This4 is my own image: http://mydomain.com/image/13/imagetitle.html, yet I recommend this one as well: image: http://mydomain.com/image/15/imagetitle2.html 
"; 
echo preg_replace('/mydomain.com(.*)image\/(\d+)\/(.*).html/', 'replaced one', $data);