gpt4 book ai didi

php - 如何使用php dom文档删除和替换标签

转载 作者:行者123 更新时间:2023-12-05 02:23:57 24 4
gpt4 key购买 nike

我有图片标签 <img src="path_to_file.png">但我希望将图片标签转换为移动网站中的链接。所以我想将 img 转换为 href:

<a href="path_to_file.png" target="_blank">Click here to open in new tab</a>

我开始使用 php dom。我可以获得列出的所有属性。

$newdocument = new DOMDocument();
$newdocument->loadHTML();
$getimagetag = $doc->getElementsByTagName('img');
foreach($getimagetag as $tag) {
echo $src=$tag->getAttribute('src');
}

但是我们如何获取 src 属性,然后完全删除 img 标签,因为它包含其他参数,如高度和长度,然后创建新的链接标签?

大家好,我可以使用以下代码从 php dom 完成它

$input="<img src='path_to_file.png' height='50'>";
$doc = new DOMDocument();
$doc->loadHTML($input);
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$src=$tag->getAttribute('src');
$a=$doc->createElement('a','click here to open in new tab');
$a->setAttribute('href',$src);
$a->setAttribute('style','color:red;');
$tag->parentNode->replaceChild($a,$tag);
}
$input=$doc->saveHTML();
echo $input;

create 元素也可用于在 <a></a> 之间放置文本即单击...新选项卡。

replacechild 用于删除 $tag 即 img并将其替换为 a标签。通过设置属性,我们可以添加其他参数,如样式、目标等。

我最后使用了 php dom,因为我只想转换从 mysql 获得的数据,而不是网站 Logo 等其他元素。当然也可以使用 javascript。

谢谢

@dave chen 用于 javascript 方式并指向检测移动链接。

@nate 指出我的答案。

最佳答案

使用phpQuery,太神奇了。就像使用 jquery 一样! :) https://code.google.com/p/phpquery/

关于php - 如何使用php dom文档删除和替换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17910616/

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