2012-01-26 39 views
0

這裏是我的代碼:關於PHP str_replace函數功能

$search = array('<script src="/', 
     '<link href="/', 
     '<a href="/', 
     '<img src="/', 
     'src="/'); 
$d = 'http://www.ifreewind.net'; 
$replace = array('<script src="'.$d.'/', 
     '<link href="'.$d.'/', 
     '<a href="'.$d.'/', 
     '<img src="'.$d.'/', 
     'src="'.$d.'/'); 
$result = str_replace($search, $replace, $contents); 

echo $result; 

這些代碼有一個問題是,它們不能取代img標籤,如:

<img width="50px" src="/..."> 

<img width="50px" src="http://www.ifreewind.net/..."> 

如何解決這個問題?

回答

1

對此,您不能使用str_replace。你可以用preg_replace嘗試:

preg_replace('~(src|href)="(?=/)~', '$1http://www.ifreewind.net', $contents); 

不過,我強烈建議你使用an HTML parser來代替。

+0

非常感謝! – Phoenix