java
sql
css
ajax
python
database
xcode
regex
mysql
objective-c
multithreading
eclipse
silverlight
perl
facebook
oracle
cocoa
mvc
asp
api
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!
preg_replace
href
src
This converts all of the above test cases correctly:
$result = preg_replace( '/(src|href)="(?:\.\.\/|\/)?([^"]+)"/i', '$1="' . $url . '/$2"', $test);
Demo
That's not really a good comparison. Those two functions serve separate purposes. I would personally use three, in this order:
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);
<?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