获取<;img>;标记


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

感觉我的答案是对的。

感谢所有回答的人!:)

您需要使用正则表达式来筛选出所需的标记。