2017-01-23 60 views
1

我有一個問題,這似乎很簡單,但誰造成我一些問題。檢測特定的網址並添加跟蹤參數PHP

我有一個文本字符串,可以包含多個html標記,段落和鏈接(文本鏈接和/或html鏈接)。我想解析內容,檢測具有特定網址的鏈接,並且只有在這種情況下,才能在網址中應用跟蹤參數。

示例:我想僅在以google.com開頭的網址上添加參數。

$string = 'This is the content... <a href="yahoo.com">Yahoo</a> - <a href="google.com">This one will be surcharged with ?tk=test</a> and direct links too : google.com"; 

我該怎麼做?我試圖用正則表達式,但它不工作。我嘗試了preg_replace,但URL可以有多種形式(使用http或者不使用,不同的tld等)。

謝謝!

回答

2

我會使用preg_replace/href="([^"?]*google\.com[^"]*)"/作爲模式。 ("在下面的PHP的轉義)

$string = 'This is the content... <a href="yahoo.com">Yahoo</a> - <a href="google.com">This one will be surcharged with ?tk=test</a>'; 

$output = preg_replace("/href=\"([^\"?]*google\.com[^\"]*)\"/", "href=\"$1?tk=test\"", $string); 

echo $output; 

返回:

This is the content... <a href="yahoo.com">Yahoo</a> - <a href="google.com?tk=test">This one will be surcharged with ?tk=test</a> 

這應該追加?tk=test到包括"google.com" https://regex101.com/r/7eoohe/3


**更新任何HREF的端部正則表達式不匹配的URL像https://search.yahoo.com/?p=google.com