Pregunta

I have this kind of string:

$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>&nbsp;</p>
    <p><img src="http://www.example.com/uploads/1925203_592726304151630_869780824_n.jpg" alt="" width="960" height="640" /></p>
    <p>&nbsp;</p>
    <p>Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus </p>
    <p>&nbsp;</p>
    <p><img src="http://www.example.com/uploads/15191240065310b76f09c67543640579_640x423.jpg" alt="" width="846" height="559" /></p>
    <p>&nbsp;</p>
    <p>&nbsp;Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus .</p>":

I need some good PHP class to only cath one img tag with attribute in php, it means in this kind of string from this kind of string i need new string like

$newstring="<img src="http://www.example.com/uploads/1925203_592726304151630_869780824_n.jpg" alt="" width="960" height="640" />';

But i need to check if there is no image tag with attribue, then i need to have other sting like this

$default="no image";

Is it possible to have that kind of new string?

Now i have something like this

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

Problem is when i dont have image i got nothing and i need only one image, no matter wwhat?

¿Fue útil?

Solución

You can use a regular expression.

$string = "your long string";
$matches = array();
// returns only one match
if (preg_match("/<img.*\/>/", $string, $matches)) {
    $newstring = reset($matches);
}
else {
    $newstring = 'no image';
}

Otros consejos

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

Using simple_html_dom:

$doc = str_get_html($str);
$newstring = ($img = $doc->find('img', 0)) ? $img->src : 'default.jpg';
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top