ai didi

php - 用另一个替换链接

转载 作者:行者123 更新时间:2023-12-04 05:08:22 24 4
gpt4 key购买 nike

我正在努力替换每个链接中的文本。

$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';

if(preg_match_all($reg_ex, $text, $urls))
{

foreach($urls[0] as $url)
{

echo $replace = str_replace($url,'http://www.sometext'.$url, $text);
}

}

从上面的代码中,我得到了 3 倍相同的文本,并且链接一个一个更改:每次只替换一个链接 - 因为我使用 foreach,我知道。
但我不知道如何一次全部更换它们。
你的帮助会很棒!

最佳答案

您不在 html 上使用正则表达式。使用 DOM相反。话虽如此,您的错误在这里:

$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---

你永远不会更新 $text,所以你在循环的每次迭代中不断地丢弃替换。你可能想要
$text = str_replace(...., $text);

相反,因此更改“传播”

关于php - 用另一个替换链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15226630/

24 4 0
文章推荐: java - 根据先前的值以原子方式插入或更新实体
文章推荐: sql - 选择单行的多列作为数组元素
文章推荐: java - 自动化 Java EE Web 应用程序的完整测试
文章推荐: sql-server - 列出特定数据库上的所有用户
行者123
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com