ereg and img tag

Hi experts

I need to retreive the value of the "src" from the tag "img" into an html string.

for exemple:
html -> this is a test <img src='test.jpg'> test
also html -> this is a test <img src="test.jpg"> test
It should return "test.jpg"
Who is Participating?
jausionsConnect With a Mentor Commented:
First, you shouldn't be using the ereg function, it's on its way out. Use PCRE functions instead... preg_match()

Here's a regular expression that actually works, and actually capture all the images if needed...
$html = array(
    'blah test <img alt="blue"
src ="image.jpg" width="12" /> test message',
    '<img src=\'test.jpg\'>',
    '<p>some text<img lowsrc="blackwhite.gif" src="fullcolor.jpg" title="Low/Res"/> <img src="icon.png" height="12"></p>',
$re = '/<img\s*[^>]*\s+src\s*=\s*([\'"])([^"\']+)\1\s*[^>]*>/im';
foreach ($html as $h) {
    // Capture all the <img> information
    preg_match_all($re, $h, $matches);
    echo "\r\n".$h.' ===> ';
    echo "\r\n";
    // Captures only the first match
    preg_match($re, $h, $matches);
    echo "\r\n".$h.' ===> '.$matches[2]."\r\n";

Open in new window

Beverley PortlockCommented:

$text = "this is a test <img src='test.jpg'> test";
$pattern = "(.*)<img src='(.+)'>(.*)";
$matches = array();

ereg( $pattern, $text, $matches );

echo "<br/>";
echo "The text you what is in the 2nd group and is '". $matches[2] . "'";
Beverley PortlockCommented:
Note: The pattern used above (.*)<img src='(.+)'>(.*) expects <image and src=' to be separated by one space and for thesrc to be delimited by apostrophes rather than double quotes.
cabouAuthor Commented:
I need a solution the works with apostrophes and double quotes

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.