我有图像标签<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获得的数据,而不想转换其他元素,比如网站的徽标。当然,也可以使用javascript。
感谢
@陈为javascript方式和指向检测移动链接。
@内特给我指了一个答案。
使用phpQuery,非常棒。这就像使用jquery!:)https://code.google.com/p/phpquery/
我建议使用JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Images Test</title>
<script>
window.onload = changeImages;
function changeImages() {
var images = document.getElementsByTagName("img");
while (images.length > 0) {
var imageLink = document.createElement("a");
imageLink.href = images[0].src;
imageLink.innerHTML = "Click here to view " + images[0].title;
images[0].parentNode.replaceChild(imageLink, images[0]);
}
}
</script>
</head>
<body>
Here is a image of flowers : <img src="images/flowers.bmp" title="Flowers" ><br>
Here is a image of lakes : <img src="images/lakes.bmp" title="Lakes" ><br>
Here is a image of computers: <img src="images/computers.bmp" title="Computers"><br>
</body>
</html>
示例