0

i'm trying to create a script that transform all the relative paths to absolute paths

so how can I find and replace in a html text all the occurences of

src="/jsfile.js

with

src="http://mysite.com/jsfile.js

then

src="../jsfile.js

with

src="http://mysite.com/jsfile.js

and then

src="js/jsfile.js

with

src="http://mysite.com/js/jsfile.js

and maybe more cases? well of course also the href scenarios

UPDATE

maybe my question was bad written, but the goal is to replace any relative url or relative link to an absolute url... i'm not sure if the answers below are working

4 Answers 4

1

How about a single regex using preg_replace? It will also work for href and src attributes. Be sure to check the demo to see it in action!

This converts all of the above test cases correctly:

$result = preg_replace( '/(src|href)="(?:\.\.\/|\/)?([^"]+)"/i', '$1="' . $url . '/$2"', $test);

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

That's not really a good comparison. Those two functions serve separate purposes. I would personally use three, in this order:

  1. preg_match: Find the URLs that need to be modified.
  2. substr: Modify the URLs.
  3. str_replace: Replace the old URLs with the modified URLs.

Comments

0

If it becomes more than 3, use

$pathes=array(
  'src="/jsfile.js' => 'src="http://mysite.com/jsfile.js',
  'src="../jsfile.js' => 'src="http://mysite.com/jsfile.js',
  'src="js/jsfile.js' => 'src="http://mysite.com/js/jsfile.js'
);


$newhtml=str_replace(array_keys($pathes),$pathes,$oldhtml);

Comments

0
<?php
$html = file_get_contents('index.html');
$html = preg_replace_callback('#"(\S+).js"#', "replace_url", $html);
function replace_url($url) {
return '"http://'.$_SERVER['HTTP_HOST'].chr(47).trim($url[1], '/,.').'.js"';
}
echo $html;

Use preg_replace_callback

1 Comment

This has some problems: 1. The . in the regex will match any character, it should be escaped (\.). 2. It will convert invalid strings, such as "node#js" to "http://mysite.com/node.js". 3. The performance of preg_replace_callback is slower than a single preg_replace as there is overhead required to execute the callback function repeatedly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.