2012-01-09 64 views
0

我是PHP新手,試圖用下面的代碼中的google.com替換URL模式。在PHP中正則表達式中轉義引號時出錯

$textStr = "Test string contains http://foo.com/more_(than)_one_(parens) 
http://foo.com/blah_(wikipedia)#cite-1 
http://foo.com/blah_(wikipedia)_blah#cite-1 
http://foo.com/unicode_(?)_in_parens 
http://foo.com/(something)?after=parens 
more urls foo.ca/me some other text"; 

$pattern = '(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)((?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»「」‘’]))*)'; 

$textStr = preg_replace($pattern, "google.com", $textStr); 

echo $textStr; 

我發現正則表達式模式在http://daringfireball.net/2010/07/improved_regex_for_matching_urls但我一直沒能成功逃脫單引號,雙引號中的格局。

目前我得到的消息 - 警告:的preg_replace()未知的修飾詞「\」 但我用斜線(),以逃避{單引號};:\'」

能有人幫我上面?

+1

[將ereg表達式轉換爲preg(缺少分隔符)](http://stackoverflow.com/questions/6270004/converting-ereg-expressions-to-preg) – mario 2012-01-09 05:56:26

回答

1

在首位preg_replace你必須劃定你的正常快遞通過/離子,如:

/\b((?:https: ... etc etc)/ 

其次,因爲你/,你必須使用反斜線任何/劃定你的正則表達式。所以https:// - >https:\/\/

`/\b((?:https: .. etc etc)/i` 

嘗試:

三,你的修飾語(?i)尾隨斜線後去(更改時間:逃脫/,搬離(?i)regex/regex/i正則表達式):

$pattern = '/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)((?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»「」‘’]))*)/i'; 
$textStr = preg_replace($pattern, "google.com", $textStr); 

echo $textStr; 

現在,由於$pattern比賽整個網址,你只需要拿出:

"Test string contains google.com 
google.com 
google.com 
google.com 
google.com 
more urls google.com some other text" 

所以總之,我建議@安培的答案(但這比正常情況下有一個寬鬆的正則表達式),或者使用捕獲括號和反向引用來做類似preg_replace($pattern,'google.com/\2',$textStr)(但適當修改您的捕獲括號,因爲這樣做不起作用與您當前的捕捉括號安排)。

This site對測試事情很有用。

+0

正則表達式分隔符不一定是'/',它幾乎可以是任何標點符號。例如,如果使用'〜',則不必轉義任何東西,因爲該字符從不出現在正則表達式中。另外,PHP支持'(?i)'(inline modifier)語法,所以你不需要改變它(但是結尾的修飾符也可以)。 – 2012-01-09 18:46:29

+0

感謝您的澄清@AlanMoore,方便知道! – 2012-01-09 23:26:27

+0

@ mathematical.coffee謝謝你的幫助。這正是我所期待的。 – James 2012-01-11 04:50:55

1
$patterrn='/([wW]{3,3}\.|)[A-Za-z0-9]+?\./'; 
$text="Test string contains http://foo.com/more_(than)_one_(parens) 
http://foo.com/blah_(wikipedia)#cite-1 
http://foo.com/blah_(wikipedia)_blah#cite-1 
http://foo.com/unicode_(?)_in_parens 
http://foo.com/(something)?after=parens 
more urls foo.ca/me some other text"; 
$output = preg_replace($patterrn,"abc.",$text); 
print_r($output); 

輸出將是代碼,

Test string contains http://abc.com/more_(than)_one_(parens) http://abc.com/blah_(wikipedia)#cite-1 http://abc.com/blah_(wikipedia)_blah#cite-1 http://abc.com/unicode_(?)_in_parens http://abc.com/(something)?after=parens more urls abc.ca/me some other text 
+0

感謝您的幫助。雖然我無法將其用於當前的需求,但在其他情況下,這肯定會很方便。 – James 2012-01-11 04:56:29

相關問題