【问题标题】:Getting the <img> tag in an HTML using PHP使用 PHP 在 HTML 中获取 <img> 标签
【发布时间】:2012-03-26 11:48:23
【问题描述】:

我的输出是这样的:

<img src="location-of-image.png" style="width:100px;height:100px" title='smpl'/>
<p>sampe sample sampple</p><br />when? how?.

我的问题是我只想得到

<img src="location-of-image.png" style="width:100px;height:100px;" title='smpl'/>

并删除

<p>sampe sample sampple</p><br />when? how?.`

所以我的预期输出应该只是这样:

<img src="location-of-image.png" style="width:100px;height:100px;" title='smpl'/>

我将如何在 PHP 中做到这一点? 我知道这在 javascript/jquery 中更容易完成,但我想要在 PHP 中。

【问题讨论】:

  • img标签是输入字符串的第一个标签吗?
  • 你的标签总是分成两行吗?

标签: php algorithm logic


【解决方案1】:

使用 PHP DOM:

$doc = new DOMDocument();
$doc->loadXML('<img src="location-of-image.png" style="width:100px;height:100px;"    title='sampletitle' /><p>sampe sample sampple</p>');

$doc = $doc->removeChild($doc->firstChild);

【讨论】:

    【解决方案2】:

    您可以使用str_replace

    $str  =  '<img src="location-of-image.png" style="width:100px;height:100px;" title='sampletitle' /><p>sampe sample sampple</p><br />when? how?.';
    
    $toBeReplaced   =  '<p>sampe sample sampple</p><br />when? how?.';
    
    
    $body = str_replace($toBeReplaced, "", $str);
    

    【讨论】:

    • 是动态的,它每次都会根据用户输出而变化。这里的一切都是动态的,上面只是一个例子。
    • 你能否捕获动态文本然后将此文本传递给此变量 $toBeReplaced=$your 动态文本。
    【解决方案3】:

    你可以使用preg_replace:

    preg_replace('^(<img.*?/>).*$', 
                 '$1',
                 '<img src="location-of-image.png" style="width:100px;height:100px;" title="sampletitle" /><p>sampe sample sampple</p><br />when? how?.');
    

    【讨论】:

      【解决方案4】:

      好吧,我想我明白了。

      这是我的答案,一个非常明显且简单的解决方案:

      $str = '<img src="location-of-image.png" style="width:100px;height:100px" title='smpl'/ <p>sampe sample sampple</p><br />when? how?.'
      
      $str = strip_tags( $str, "<img>"); #For safety precaution.
      
      $first = strpos($str, '<img ');
      $last = strpos($str, '/>');
      echo "<".substr( $str ,1,$last+1 );
      

      感觉我的答案是对的。

      感谢所有回答的人! :)

      【讨论】:

        【解决方案5】:

        你需要使用正则表达式来过滤掉你想要的标签。

        【讨论】:

        • 这是一个毫无价值的答案。这就像在说“你可以用编程来解决问题”。
        • 我知道正则表达式一文不值。但我不知道还有其他选择。
        • @Hammerite 规则是不要使用正则表达式来操作 arbitrary HTML,但是如果 OP 的字符串始终遵循相同的格式(即它是常规的),那么正则表达式就可以了.
        • @KishoreK 如果你知道你的答案是废话,你为什么还要回答?
        • @Juhana 再次阅读我的评论!不是每个人都能给出最好的解决方案。任何人都可以表达他们的想法,即使它很糟糕。你不能说他们根本不回答。
        猜你喜欢
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2014-08-22
        相关资源
        最近更新 更多