2017-01-23 6 views
1

私は質問がありました。特定のURLを検出して追跡パラメータを追加するPHP

私は複数のhtmlタグ、段落、リンク(テキストリンクやHTMLリンク)を含むことができるテキスト文字列を持っています。私はコンテンツを解析し、特定のURLを持つリンクを検出し、この場合にのみ、URLに追跡パラメータを適用したいと思います。

例:google.comで始まるURLにのみパラメータを追加します。

$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[^"]*)"/をパターンとして使用します。これは、"google.com" https://regex101.com/r/7eoohe/3


**更新含む任意のhrefの末尾に?tk=testを追加する必要があり

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> 

$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; 

戻り値を("は、以下のPHPでエスケープされます) URLと一致しない正規表現https://search.yahoo.com/?p=google.com

関連する問題