gpt4 book ai didi

php - 查找特定域名并在字符串 PHP 中附加 url

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:10 24 4
gpt4 key购买 nike

假设我有以下字符串:

<?php
$str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';
?>

我想做的是在字符串中找到具有特定域名的 URL,本例中为“foo.com”,然后附加该 url。

我要实现的目标:

<?php
$str = 'To subscribe go to <a href="http://foo.com/subscribe?package=2">Here</a>';
?>

如果 url 中的域名不是 foo.com,我不希望附加它们。

最佳答案

您可以使用 parse_url() 函数和 php 的 DomDoccument 类来操作 url,如下所示:

$str = 'To subscribe go to <a href="http://foo.com/subscribe">Here</a>';

$dom = new DomDocument();
$dom->loadHTML($str);
$urls = $dom->getElementsByTagName('a');

foreach ($urls as $url) {
$href = $url->getAttribute('href');
$components = parse_url($href);
if($components['host'] == "foo.com"){
$components['path'] .= "?package=2";
$url->setAttribute('href', $components['scheme'] . "://" . $components['host'] . $components['path']);
}
$str = $dom->saveHtml();
}
echo $str;

输出:

To subscribe go to [Here]
^ href="http://foo.com/subscribe?package=2"

引用资料如下:

关于php - 查找特定域名并在字符串 PHP 中附加 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com