去除标签,但保留第一个标签。

3
如何保留第一个标签,但去除其他所有的标签?(来自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
示例字符串,请和您的尝试。 - Michael Petrotta
另外,用PHP解析HTML并不是一个好主意(虽然我想我们都曾经这样做过)。如果你可以重新定义问题以避免这种情况,请这么做。 - Jon
但是我需要以某种方式使用PHP来完成它。 - Anda
那里只有一个 img 标签。我假设进一步的 img 标签可能会在任何时候出现? - Michael Petrotta
3
使用HTML解析器:https://dev59.com/EnA65IYBdhLWcg3w4C-j - Arnaud Le Blanc
显示剩余2条评论
2个回答

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

你也许可以使用复杂的正则表达式字符串来实现这个功能,但是我的建议是使用 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.
});

这是一个不完整的答案,会让提问者走向错误的方向。PHP具有本地HTML DOM解析功能,还有第三方工具可以更轻松地使用它,DOM操作是更适合此任务的方法。 - Peter Boughton
我尊重你的意见。虽然PHP确实具有DOM解析功能,但你也没有为他提供这个链接:http://www.php.net/manual/en/book.dom.php - 从简单性的角度来看,这是一个简单的解决方案。至于不提供完整的代码,我认为没有必要编写所有的代码,而是提供框架,让他自己想出如何使用它。 - Howard Lince III
我没有提供链接,因为它们已经在问题的评论和一个后续问题的答案中提供了。follow-up question - Peter Boughton
提供一个框架通常是可以的,但你并没有真正解释它,也没有指出应该小心使用它。而且这个解决方案非常简单,你可能只需要添加逻辑来判断“如果是第一张图片,则返回匹配的文本,否则返回空字符串”,因为这基本上就是缺少的(好吧,还有更新正则表达式以仅处理img标签) - 这就是我说它不完整的原因。 - Peter Boughton
(注:希望这不会让人觉得我在抱怨或者什么的——我的意图是要建设性地表达意见。) - Peter Boughton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接