0

I am using drupal and have a variable that contains loads of html. What I want to do is select the first image that appears in that html, capture the image src so that I can manipulate the image in other ways and then remove all images from the html. I should now have a variable containing the captured first image source, and a variable containing the html minus any images.

To place the first image into a variable I have tried -

    $texthtml =  $node->teaser;
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
echo $image['src'];

This works fine so long as the image code follows the following logic - 'img src..' however thanks to my content management system, some img tags dont place 'src' straight after 'img' such as - 'img class..'. In this instance the above code only takes the first image that follows the specific order of 'img src..' How do I do this where the img code can be in any order?

To then remove the image from the original string I am successfully using -

 $stripped = $node->teaser;
$stripped = preg_replace("/<img[^>]+\>/i", "(image) ", $stripped); 
echo $stripped;

Thanks!

4

1 回答 1

0

使用以下,

preg_match_all('/\<img(.*?)\/\>/', $texthtml, $matches);
于 2012-08-26T17:55:19.430 回答