去掉标签,但保留第一个 [英] Strip tags, but keep the first one

查看:130
本文介绍了去掉标签,但保留第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何保留例如第一个 img 标签但剥离所有其他标签?

HTML字符串)

示例:

 < p> 
some text
< img src =aimage.jpgalt =descwidth =320height =200/>
< img src =aimagethatneedstoberemoved.jpg... />
< / p>

所以它应该是:

 < p为H. 
some text
< img src =aimage.jpgalt =descwidth =320height =200/>
< / p>


解决方案

这个例子中的函数可以用来保持前N个IMG标签,并删除所有其他< img> s。

  //在$ str中保留第一个$ nrimg IMG标签的功能,并将所有其他的< img> s 
//从//开始:http://coursesweb.net/php-mysql/
函数keepNrImgs($ nrimg,$ str){
//获取一个包含al< img>的数组(preg_match_all('/(\< img [^ \>] + \>)/ i',$ str,$ mt)){
/ /使用必须被剥离的< img>获取数组($ nrimg +),并将它们删除
$ remove_img = array_slice($ mt [1],$ nrimg);
$ str = str_ireplace($ remove_img,'',$ str);
}
返回$ str;
}

//测试,将前两个IMG标记保存在$ str
$ str ='First img:< img src =img1.jpgalt = img 1width =30/>,第二张图片:< img src =img_2.jpgalt =img 2width =30> ;,另一个Img标签< img src =img3。 jpgalt =img 3width =30/>等等。
$ str = keepNrImgs(2,$ str);
echo $ str;
/ *输出:
第一张图片:< img src =img1.jpgalt =img 1width =30/>,第二张图片:< img src =img_2 .jpgalt =img 2width =30>,另一个Img标签,...等等
* /


How can I keep for example the first img tag but strip all the others?

(from a HTML string)

example:

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

so it should be just:

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

解决方案

The function from this example can be used to keep the first N IMG tags, and removes all the other <img>s.

// 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.
*/

这篇关于去掉标签,但保留第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆