2014-04-07 12 views
0

我嘗試更換所有IMG SRC是不包含完整的URL與完整的圖像URLPHP:在一定條件下更換每IMG SRC

例如像這樣

<?php 
$html_str = "<html> 
      <body> 
       Hi, this is the first image 
        <img src='image/example.jpg' /> 
       this is the second image 
        <img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' /> 
       and this is the last image 
        <img src='image/last.png' /> 
      </body> 
     </html>"; 

?> 

當頂替成了這個樣子

<?php 
$html_str = "<html> 
      <body> 
       Hi, this is the first image 
        <img src='http://example.com/image/example.jpg' /> 
       this is the second image 
        <img src='http://sciencelakes.com/data_images/out/14/8812836-green-light-abstract.jpg' /> 
       and this is the last image 
        <img src='http://example.com/image/last.png' /> 
      </body> 
     </html>"; 

?> 

那麼如何檢查每個img src那個不完整的鏈接並替換它呢? ($的是html_str動態的基於MySQL的)

,請給我一些解決這個問題

感謝

回答

2

我想它正確地使用DOM庫做的,如

$doc = new DOMDocument(); 
$doc->loadHTML($html_str); 

$xp = new DOMXPath($doc); 
$images = $xp->query('//img[not(starts-with(@src, "http:") or starts-with(@src, "https:") or starts-with(@src, "data:"))]'); 
foreach ($images as $img) { 
    $img->setAttribute('src', 
     'http://example.com/' . ltrim($img->getAttribute('src'), '/')); 
} 
$html = $doc->saveHTML($doc->documentElement); 

在這裏演示 - http://ideone.com/4K9pyD

0

試試這個:

你可以使用下面的代碼獲得圖片來源:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html)); 
$src = $xpath->evaluate("string(//img/@src)"); 

之後檢查字符串包含http與否。根據做的操作。