James
James

Reputation: 43647

PHP single quotes regex

This topic is a remark for 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&d=identicon&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&d=identicon&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&d=identicon&r=PG'
[1] => http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&d=identicon&r=PG
)

Don't need the first value in array.

Thanks.

Upvotes: 2

Views: 891

Answers (1)

strager
strager

Reputation: 90022

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.

Upvotes: 3

Related Questions