add site url only if it is missing

2019-09-08 15:18发布

问题:

I need to alter the text in some places which was having missing site url.

Suppose I have a big html code, in that code some places the site url is missing, but some places it has.

Example : /blog/images/image.png need to alter http://www.domain.com/blog/images/image.png

So I have tried following code,

$html=preg_replace('%/blog/%','http://www.domain.com/blog/',$html);

But with this code it alter the following lines as well,

http://www.domain.com/blog/images/image.png -> http://www.domain.com/http://www.domain.com/blog/images/image.png

How should I skip that ?

Basically I need to add the site url(http://www.domain.com/) to some places only if it is missing.

回答1:

Its little tricky. Just remove the http://www.domain.com/ from url and add http://www.domain.com/manually to url.

Try

$html = "http://www.domain.com/".str_ireplace('http://www.domain.com/','',$html);

OR

Find the values where http://www.domain.com/http://www.domain.com/ add two times and replace it with http://www.domain.com/

Try

$html = preg_replace('%/blog/%','http://www.domain.com/blog/',$html);
$html = str_ireplace('http://www.domain.com/http://www.domain.com/','http://www.domain.com/',$html);

OR (solution by @anonymous)

$html = preg_replace('@(http://www.domain.com)?/blog@iU', 'http://www.domain.com/blog', $html)