tags:

views:

42

answers:

1

This topic is a remark for http://stackoverflow.com/questions/3510535/php-get-image-src

So we have a variable with code inside (only image):

$image = "<img src='http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG' height='32' width='32' alt=''/>";

How can we get src of this image? We should throw it to some new variable.

Want to use regex, tryed this (doesn't work):

preg_match('@src=\'([^"]+)\'@', $image, $src);

The problem is - there are single quotes instead of double quotes.

Finally, we must get:

$src = 'http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG';

Searching for a true regex.


If I use '@src=\'([^"]+?)\'@', print_r($src) gives:

Array (
[0] => src='http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG'
[1] => http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG
)

Don't need the first value in array.

Thanks.

+3  A: 

The expression [^"]+ is being greedy. To make it stop matching as soon as ' is reached, use [^"]+?.

I assume you meant [^']+. Writing this will also fix your problem.

Finally, assign $src to $src[1] to get the first grouped expression.

strager
'@src=\'([^"]+?)\'@' - still doesn't work as expected
Happy
Happy
@WorkingHard, Can you enclose the code in backticks (`)?
strager
@strager, updated a question
Happy
@WorkingHard, Updated answer.
strager
Greediness wouldn't be an issue if he just corrected the character class as you suggested. By the way, the single-quote in the character class needs to be escaped like the others, i.e., `[^\']+`
Alan Moore