php - 查找所有超链接并在文本中添加另一个重定向链接
问题描述
我想在文本中查找所有超链接并向每个链接添加链接重定向示例文本
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>
解决方案
$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
。
推荐阅读
- ios - Swift UIBarButtonItem 标题
- android - 我得到了 db.update() 值 1 但是当我从数据库中获取所有数据时,SQLite 数据库中的行都没有受到影响
- c# - 如何在列表中添加带参数的方法
- php - 需要从这个数组中提取结果
- ruby-on-rails - 来自 sidekiq 的 Action Cable Broadcast 消息仅在刷新后显示,可从控制台立即运行
- python - 将模型内的Keras Model层变成多层
- kakoune - 如何选择圆括号?
- javascript - 使用 onclick 将多个参数传递给函数
- symfony - 如何在 Symfony 中翻译整页?
- javascript - 用于 css\scss url 导入的 webpack 递归加载器