0

I use this code:

<?php
    $texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
    echo $image['src'];
?>

However, when I test it, I get last image (3.png) from a string.

I want to know how can I do for get first image (1.jpeg) in a string.

Siegmeyer
  • 4,312
  • 6
  • 26
  • 43

2 Answers2

0

Try:

preg_match('/<img(?: [^<>]*?)?src=([\'"])(.*?)\1/', $texthtml, $image);
echo isset($image[1]) ? $image[1] : 'default.png';
Taufik Nurrohman
  • 3,329
  • 24
  • 39
0

Regex is not suitable for html tags.
You can read about it here: RegEx match open tags except XHTML self-contained tags

I suggest DOM document if it's more complex than what you have shown here.
If it's not more complex than this I suggest strpos to find the words and "trim" it with substr.

$texthtml = '<p>test</p><br><p><img src="1.jpeg" alt=""><br></p><p><img src="2.png" alt=""><br><img src="3.png" alt=""></p>';
$search = 'img src="';
$pos = strpos($texthtml, $search)+ strlen($search); // find postition of img src" and add lenght of img src"
$lenght= strpos($texthtml, '"', $pos)-$pos; // find ending " and subtract $pos to find image lenght.

echo substr($texthtml, $pos, $lenght); // 1.jpeg

https://3v4l.org/48iiI

Andreas
  • 23,610
  • 6
  • 30
  • 62