php怎么实现在图片上做标记,如何在PHP中在图像下方添加noscript标记?

该博客介绍了如何通过DOMDocument在文章内容的每个<img>标签中添加<noscript>元素。代码示例展示了遍历HTML中的图片,获取src属性,并创建<noscript>标签插入原始图片的前部,以备JavaScript不可用时仍能显示图片。最后,将更新后的HTML内容返回。
摘要由CSDN通过智能技术生成

更新现有对象(或数组)时,如果通过引用工作,foreach循环要注意的事项

默认情况下,foreach循环创建项的副本并在其上运行。要使用实际对象,应在前面添加

我还注意到在实际的dom分配中使用临时变量:

创建临时变量并使用其结果插入对象

但它应该行得通

我还让saveHTML脱离了循环,因为不需要中间保存

希望有帮助

下面是&img

add_filter('the_content', function ($content) {

$dom = new DOMDocument();

$dom->loadHTML($post->post_content);

foreach($dom->getElementsByTagName( 'img' ) as &$img) {

if ( $img->hasAttribute( 'src' )) {

$src_attr = $img->getAttribute( 'src' );

$noscript = $dom->createElement( 'noscript' );

$noscript_node = $img->parentNode->insertBefore( $noscript, $img );

$noscript_img = $dom->createElement( 'IMG' );

$new_img = $noscript_node->appendChild( $noscript_img );

$new_img->setAttribute( 'src', $src_attr );

}

};

$content = $dom->saveHTML();

return $content;

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值