【问题标题】:Detect specific url and add tracking parameters PHP检测特定 url 并添加跟踪参数 PHP
【发布时间】:2017-06-08 07:47:41
【问题描述】:

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

我有一个文本字符串,它可以包含多个 html 标记、段落和链接(文本链接和/或 html 链接)。我想解析内容,检测带有特定 URL 的链接,并且仅在这种情况下,在 url 中应用跟踪参数。

示例:我只想在以 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 等)。

谢谢!!!

【问题讨论】:

    标签: php regex parameters preg-replace


    【解决方案1】:

    我会使用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" 的任何href 的末尾 https://regex101.com/r/7eoohe/3


    **更新正则表达式以不匹配像https://search.yahoo.com/?p=google.com这样的网址

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    相关资源
    最近更新 更多