首页 > 解决方案 > 查找所有超链接并在文本中添加另一个重定向链接

问题描述

我想在文本中查找所有超链接并向每个链接添加链接重定向示例文本

Hello Visit our website <a href="http://example.com">Here</a>

我想要的结果是

Hello Visit our website <a href="https://mywebsite.com?q=http://example.com">Here</a>

我试过的代码

    $reg_exUrl = "/<a\s[^>]*href=(\\\" ??)([^\\\" >]*?)\\1[^>]*>(.*)<\/a>/siU";
$text = 'Hello visit our website <a href="https://example.com">Book</a>';
if(preg_match($reg_exUrl, $text, $url)) {
    echo preg_replace($reg_exUrl, '<a href="http://mywebsite.com?q='.$url[0].'">'.$url[2].'</a>', $text);

} else {
    echo $text;
}

所以我的代码的结果是

Hello visit our website Book">https://example.com

HTML 检查中的哪个是

Hello visit our website <a href="http://mywebsite.com?q=<a href="https://example.com">Book</a>">https://example.com</a>

标签: phpregex

解决方案


$text = preg_replace_callback('@(<a[^>]+href=")([^"]+)(")@', 'add_track_callback', $text);

function add_track_callback($matches){
    $track_url_base = 'https://mywebsite.com?q=';
    return $matches[1] . $track_url_base . urlencode($matches[2]) . $matches[3];
}

根据需要进行更改$track_url_base


推荐阅读