我有一个带有HTML内容的字符串(在Wordpress中),我想用另一个URL替换图像标记周围的每个链接URL:
Before: <a href="A"><img src="X"></a>
After: <a href="B"><img src="X"></a>
首先我想用正则表达式做,但后来我读到这根本不推荐。那么有可能用PHP做到这一点吗?
答案 0 :(得分:5)
使用DOM API
$doc = new DOMDocument();
$doc->loadHTML($htmlString, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// the flags are for if you're not using a complete document, ie an HTML fragment
// You'll need the libxml extension enabled
$xpath = new DOMXPath($doc);
// find all <a> tags with an "href" attribute and <img> child element
$links = $xpath->query('//a[@href and img]');
foreach ($links as $link) {
$link->setAttribute('href', 'B');
}
$newHtmlString = $doc->saveHTML();
答案 1 :(得分:0)
是的,您可以使用 DOMDocument :
轻松完成$dom = new DOMDocument();
$dom->loadHTML('<a href="A"><img src="X"></a>');
foreach ($dom->getElementsByTagName('a') as $item) {
$item->setAttribute('href', 'B');
echo $dom->saveHTML();
}