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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.