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"
cabouAsked:
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...
<?php
 
$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.' ===> ';
    print_r($matches[2]);
    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

0
 
Beverley PortlockCommented:
<?php

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

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

print_r($matches);
echo "<br/>";
echo "The text you what is in the 2nd group and is '". $matches[2] . "'";
?>
0
 
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.
0
 
cabouAuthor Commented:
I need a solution the works with apostrophes and double quotes

thanks
0
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.