Strip tags, but keep the first one

ⅰ亾dé卋堺 提交于 2019-12-19 04:09:27

问题


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>

回答1:


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



回答2:


You might be able to accomplish this with a complex regex string, however my suggestion would be to use preg_replace_callback, particularly if you are on php 5.3+ and here's why. http://www.php.net/manual/en/function.preg-replace-callback.php

$tagTracking = array();
preg_replace_callback('/<[^<]+?(>|/>)/', function($match) use($tagTracking) {
    // your code to track tags here, and apply as you desire.
});


来源:https://stackoverflow.com/questions/7457650/strip-tags-but-keep-the-first-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!