剥离标签,但保留第一个

时间:2011-09-17 20:42:58

标签: php html string strip-tags

我如何保留第一个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>

2 个答案:

答案 0 :(得分:0)

此示例中的函数可用于保留前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.
*/

答案 1 :(得分:-1)

您可以使用复杂的正则表达式字符串完成此操作,但我的建议是使用preg_replace_callback,特别是如果您使用的是php 5.3+,这就是原因。 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.
});