我有这种字符串:
$string='<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id </p>
<p>Lorem ipsum</p>
<p> </p>
<p><img src="http://www.example.com/uploads/1925203_592726304151630_869780824_n.jpg" alt="" width="960" height="640" /></p>
<p> </p>
<p>Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus </p>
<p> </p>
<p><img src="http://www.example.com/uploads/15191240065310b76f09c67543640579_640x423.jpg" alt="" width="846" height="559" /></p>
<p> </p>
<p> Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus .</p>":
我需要一些优秀的PHP类才能在php中使用属性的一个img标签,这意味着在这种字符串中我需要新的字符串
$newstring="<img src="http://www.example.com/uploads/1925203_592726304151630_869780824_n.jpg" alt="" width="960" height="640" />';
但是我需要检查是否没有带有attribue的图像标签,然后我需要有这样的其他刺痛
$default="no image";
是否有可能拥有这种新字符串?
现在我有类似的东西
<?php
$html = new simple_html_dom();
$html->load('<html><body><img src="image/profile.jpg" alt="profile image" /></body></html>');
$imgs = $html->find('img');
foreach($imgs as $img)
print($img->src);
?>
问题是,当我没有图像时,我什么都没有,我只需要一张图片,无论什么时候?
答案 0 :(得分:1)
您可以使用正则表达式。
$string = "your long string";
$matches = array();
// returns only one match
if (preg_match("/<img.*\/>/", $string, $matches)) {
$newstring = reset($matches);
}
else {
$newstring = 'no image';
}
答案 1 :(得分:1)
$html = new simple_html_dom();
$html->load('<html><body><img src="image/profile.jpg" alt="profile image" /></body></html>');
$imgs = $html->find('img');
if (count($imgs) == 0) {
echo "no images in string";
} else {
foreach($imgs as $img)
print($img->src);
}
答案 2 :(得分:0)
使用simple_html_dom:
$doc = str_get_html($str);
$newstring = ($img = $doc->find('img', 0)) ? $img->src : 'default.jpg';