【问题标题】:Strip tags, but keep the first one剥离标签,但保留第一个
【发布时间】:2011-11-19 10:27:03
【问题描述】:

我怎样才能保留例如第一个 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>

【问题讨论】:

  • 请提供示例字符串以及您的尝试。
  • 另外,用 PHP 解析 HTML 也不是一个好主意(尽管我猜我们都曾经做过这件事)。如果您可以重新定义问题以避免这种情况,请这样做。
  • 但我需要以某种方式使用 PHP 来完成
  • 那里只有一个img 标签。我假设更多img标签可能会出现在任何时候?
  • 使用 HTML 解析器:stackoverflow.com/questions/3577641/…

标签: php html string strip-tags


【解决方案1】:

本例中的函数可用于保留前 N 个 IMG 标签,并删除所有其他 &lt;img&gt;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】:

    您也许可以使用复杂的正则表达式字符串来完成此操作,但是我的建议是使用 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.
    });
    

    【讨论】:

    • 这是一个不完整的答案,并将 OP 指向错误的方向。 PHP 具有原生 HTML DOM 解析功能,加上第三方工具,使其更易于使用,而 DOM 操作是一种更合适的方法。
    • 我尊重你的意见。虽然 PHP 确实具有 DOM 解析功能,但您也没有为他提供,这里:php.net/manual/en/book.dom.php - 这是一个简单的解决方案。至于不提供完整的代码,我觉得没必要把所有的代码都做完,而是提供框架让他自己想怎么用。
    • 我没有提供这些链接,因为它们已经提供了,既可以作为对问题的评论,也可以作为对 follow-up question 的回答。
    • 提供一个框架一般来说没问题,但你没有真正解释它,也没有指出它应该小心使用,它是这样一个简单的解决方案,您可能刚刚添加了逻辑来说“如果第一张图像,返回匹配的文本,否则返回空字符串”,因为这基本上就是缺少的所有内容(好吧,正则表达式更新为只迎合 img 标签) - 这就是为什么我'我说它不完整。
    • (p.s. 希望这不会让人觉得很奇怪/随便——我的意图是有建设性的)
    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多