gpt4 book ai didi

php - 剥离标签,但保留第一个

转载 作者:太空宇宙 更新时间:2023-11-04 13:29:12 28 4
gpt4 key购买 nike

我怎样才能保留第一个 img 标签而去掉所有其他标签?

(来自 HTML 字符串)

例子:

<p>
some text
<img src="aimage.jpg" alt="desc" width="320" height="200" />
<img src="aimagethatneedstoberemoved.jpg" ... />
</p>

所以它应该只是:

<p>
some text
<img src="aimage.jpg" alt="desc" width="320" height="200" />
</p>

最佳答案

此示例中的函数可用于保留前 N 个 IMG 标签,并删除所有其他 <img>

// Function to keep first $nrimg IMG tags in $str, and strip all the other <img>s
// From: http://coursesweb.net/php-mysql/
function keepNrImgs($nrimg, $str) {
// gets an array with al <img> tags from $str
if(preg_match_all('/(\<img[^\>]+\>)/i', $str, $mt)) {
// gets array with the <img>s that must be stripped ($nrimg+), and removes them
$remove_img = array_slice($mt[1], $nrimg);
$str = str_ireplace($remove_img, '', $str);
}
return $str;
}

// Test, keeps the first two IMG tags in $str
$str = 'First img: <img src="img1.jpg" alt="img 1" width="30" />, second image: <img src="img_2.jpg" alt="img 2" width="30">, another Img tag <img src="img3.jpg" alt="img 3" width="30" />, etc.';
$str = keepNrImgs(2, $str);
echo $str;
/* Output:
First img: <img src="img1.jpg" alt="img 1" width="30" />, second image: <img src="img_2.jpg" alt="img 2" width="30">, another Img tag , ... etc.
*/

关于php - 剥离标签,但保留第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7457650/

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