繁体   English   中英

得到 <img> 使用PHP在HTML中标记

[英]Getting the <img> tag in an HTML using PHP

我有这样的输出:

<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中完成。

使用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);

您可以使用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);

您可以使用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?.');

好吧,我想我知道了。

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

$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 );

感觉就像我正确回答了这个问题。

感谢所有回答的人! :)

您需要使用正则表达式来过滤出所需的标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM