Question

Can someone help me out, I'm poor with regex. I've got this regex to run a preg_replace on relative URL's, prepending the domain to the beginning and making them absolute. It works well for standard URL's, but I'm running into URL's that are like this:

<img src="//domain.com/file.jpg"> .

..which matches the regex and is then becoming something like:

<img src="http://www.newdomain.com//domain.com/file.jpg">, which obviously breaks.

How can I modify this regex to not accept strings that begin with two slashes '//'?

preg_replace("#(<\s*img\s+[^>]*src\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1' .$url. '/$2$3', $html);
Was it helpful?

Solution

You already are excluding URLs that have "http", you can add "//" to that -

(<\s*img\s+[^>]*src\s*=\s*[\"'])(?!(http)|(\/\/))([^\"'>]+)([\"'>]+)
                                   ^^^^^^^^^^^^^ Modified here

You can test it here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top