Php 检测特定url并添加跟踪参数

Php 检测特定url并添加跟踪参数,php,regex,parameters,preg-replace,Php,Regex,Parameters,Preg Replace,我有一个问题,看起来很简单,但谁给我带来了一些问题 我有一个文本字符串,它可以包含多个html标记、段落和链接(文本链接和/或html链接)。我希望解析内容,检测具有特定URL的链接,并且仅在这种情况下,在URL中应用跟踪参数 示例:我只想在以google.com开头的URL上添加参数 $string = 'This is the content... <a href="yahoo.com">Yahoo</a> - <a href="google.com">T

我有一个问题,看起来很简单,但谁给我带来了一些问题

我有一个文本字符串,它可以包含多个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";
$string='这是内容…-还有直接链接:google.com”;
我怎么做呢?我试过使用regex,但它不起作用。我试过使用preg_replace,但URL可以有多种形式(是否使用http、不同的tld等)


谢谢!!!

我会使用
preg\u replace
替换为
/href=“([^”]*google\.com[^”]*)/
作为模式。(
在下面的php中转义)

$string='这是内容…-';
$output=preg\u replace(“/href=\”([^\“?]*google\.com[^\“]*)\”/“,“href=\”$1?tk=test\”,$string);
echo$输出;
返回:

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”



**更新的正则表达式与URL不匹配,如
https://search.yahoo.com/?p=google.com

更新答案。谢谢spencer!这是一个很好的首次亮相。但我也希望拦截像google.com那样没有标签的直接链接。另外,如何检测具有子页面(如google.com/page)的URL?谢谢从这里的示例()中可以看到,它确实检测带有子页面的URL。至于你所说的“直接链接”,我会为子字符串“google.com”
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>