本文实例讲述了php限制html内容中图片必须是本站的方法。分享给大家供大家参考。具体实现方法如下:
1. PHP代码如下:
<?php
$dom = new DOMDocument;
$dom->loadHTML(file_get_contents('input.html'));
$xpath = new DOMXpath($dom);
$img = $xpath->query('//img');
foreach($img as $i) {
$url = parse_url($i->getAttribute('src'));
if(isset($url['host']) && in_array($url['host'], array('yourdomain.com', 'www.yourdomain.com')) == false) {
// show an error
// -- or --
// remove the tag: $i->parent->removeChild($i)
echo sprintf('[FAIL] %s' . PHP_EOL, $i->getAttribute('src'));
}
else {
echo sprintf('[PASS] %s' . PHP_EOL, $i->getAttribute('src'));
}
}
2. 测试HTML代码:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>@@##@@</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2337">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/175946161464083.png" alt="必应图像创建器">
</a>
<div class="aritcle_card_info">
<a href="/ai/2337">必应图像创建器</a>
<p>微软必应出品的AI绘图工具</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="必应图像创建器">
<span>453</span>
</div>
</div>
<a href="/ai/2337" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="必应图像创建器">
</a>
</div>
<p>@@##@@</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<p>@@##@@</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<p>@@##@@</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
3. 运行结果:
[PASS] /image.jpg [PASS] http://www.bkjia.com/uploads/allimg/160206/1559594622-0.jpg [PASS] http://www.bkjia.com/uploads/allimg/160206/1559595506-1.jpg [FAIL] http://otherdomain.com/image.jpg
转载自:http://www.aspnetjia.com



PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号