2011-12-15 91 views
0

什麼是正則表達式模式(在PHP中)用鏈接替換img字符串,其中標記img URL用作鏈接的錨文本?例如:如何將包含img網址的網址更改爲img其他鏈接?

function foo($uri) { 
    $url = parse_url($uri); 
    $paths = explode('/', $url['path']); 
    return sprintf("%s://%s/%s", $url['scheme'], 'http://mywebsite.com', end($paths)); 
} 
$str='text <img src="http://example.com/images1.jpg" />text <img src="http://example.com/img/images2.jpg" /> ending text'; 
$url = '?<=img\s+src\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22]'; 
$str_rep = preg_replace($url, foo($url), $str); 
echo $str_rep; 

變爲:

text <img src="http://mywebsite.com/images1.jpg" /> 
text <img src="http://mywebsite.com/images2.jpg" /> ending text 

如何適應呢?

+1

有你的榜樣有鬼。 – Maerlyn 2011-12-15 07:09:15

回答

0

解析(x)帶正則表達式的HTML is usually a bad idea。我提出以下基於DOM的解決方案:

$html = 'text <img src="http://mywebsite.com/images1.jpg" />' . "\n" 
    . ' text <img src="http://mywebsite.com/images2.jpg" /> ending text'; 

$domd = new DOMDocument(); 
libxml_use_internal_errors(true); 
$domd->loadHTML($html); 
libxml_use_internal_errors(false); 

foreach ($domd->getElementsByTagName("img") as $image) { 
    $link = $domd->createElement("a"); 
    $link->setAttribute("href", $image->getAttribute("src")); 
    $image->parentNode->replaceChild($link, $image); 
    $link->appendChild($image); 
} 

//this loop is neccesary so there's no doctype, html and 
// some other tags added to the output 
$doc = new DOMDocument(); 
foreach ($domd->documentElement->firstChild->childNodes as $child) 
    $doc->appendChild($doc->importNode($child, true)); 

var_dump($doc->saveHTML()); 

輸出是:

<p>text <a href="http://mywebsite.com/images1.jpg"><img src="http://mywebsite.com/images1.jpg"></a> 
text <a href="http://mywebsite.com/images2.jpg"><img src="http://mywebsite.com/images2.jpg"></a> ending text</p>