Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ajvanho's avatar
Level 14

Take src url from img with regex

I try this, but without result

/src="([^"]+)"/
0 likes
3 replies
MichalOravec's avatar
Level 75

What does it mean without result?

$string = 'A text <img src="https://google.com" alt="Google">';

preg_match('/src="([^"]+)"/', $string, $matches);

$matches[1]; // https://google.com

or with multiple images

$string = 'A text <img src="https://google.com"> and again <img src="https://laracsts.com">';

preg_match_all('/src="([^"]+)"/', $string, $matches);

$matches[1]; // ['https://google.com', 'https://laracsts.com']
1 like
CorvS's avatar

@ajvanho What exactly is it you are trying to achieve? You can grab the URL between the " of the src attribute using src="(.*?)", that way the URL is available inside the $1 parameter.

naomiperez19886@gmail.com's avatar

By the way this assumes that you would not start a tag without properly closing it. Perhaps better is

<img [^>]src="([^"]+)"[^>]>

It is unclear what you are trying to achieve, and I get the feeling I am wasting my time trying to help you. In your edit, you wrote that you tried:

preg_match_all('/(href|src)\s*=\s*"([^\s]+//[^/]+./[^\s]+.(jpg|jpeg|png|gif|bmp))/ixu'

Why is there no mention of img? Why do you include href, when img tags do not take the href attribute? It seems as though you are more interested in checking whether something is a valid image URL than in matching some URL that is specified inside an img tag. Note that the regex I provided does not check the validity of the URL; it just goes based on the fact that whatever appears in quotes in the src attribute is expected to be a valid URL. I did it this way because it is a practical assumption in many situations, and you weren't specific about what you really want. I will not update further if you can't ask a better question.

https://www.prepaidgiftbalance.vip/

Please or to participate in this conversation.