Make relative links absolute

I am requesting the source code of the website as follows:

<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); echo $txt; ?> 

Bu I would like to replace relative links with absolute ones! Primarily,

 <img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/> 

should be replaced by

 <img src="http://domain.com/images/legend_15s.png"/> 

and

 <img src='http://domain.com/images/legend_15s.png'/> 

respectively. How can i do this?

+6
source share
3 answers

This code replaces only links and images:

 <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); $txt = str_replace(array('href="', 'src="'), array('href="http://stats.pingdom.com/', 'src="http://stats.pingdom.com/'), $txt); echo $txt; ?> 

I tested and worked :)

UPDATED

Here the regex is made and works better:

 <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); $domain = "http://stats.pingdom.com"; $txt = preg_replace("/(href|src)\=\"([^(http)])(\/)?/", "$1=\"$domain$2", $txt); echo $txt; ?> 

Done: D

+7
source

This can be achieved as follows:

 <?php $input = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); $domain = 'http://stats.pingdom.com/'; $rep['/href="(?!https?:\/\/)(?!data:)(?!#)/'] = 'href="'.$domain; $rep['/src="(?!https?:\/\/)(?!data:)(?!#)/'] = 'src="'.$domain; $rep['/@import[\n+\s+]"\//'] = '@import "'.$domain; $rep['/@import[\n+\s+]"\./'] = '@import "'.$domain; $output = preg_replace( array_keys($rep), array_values($rep), $input ); echo $output; ?> 

Which will output the links as follows:

/something

will become

http://stats.pingdom.com//something

and

../something

will become

http://stats.pingdom.com/../something

But he will not edit "data: image / png;" or anchor tags.

I am sure that regular expressions can be improved.

+9
source

You do not need php, you just need to use the html5 base tag and put your php code in the html body, you only need to do the following Example:

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <base href="http://yourdomain.com/"> </head> <body> <? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741'); echo $txt; ?> </body> </html> 

and all files will use an absolute URL

+1
source

Source: https://habr.com/ru/post/910998/


All Articles