简体   繁体   English

用PHP替换图像标签周围的链接

[英]Replacing links around image tags with PHP

I have a string (in Wordpress) with HTML content and I want to replace every link URL around an image tag with another URL: 我有一个包含HTML内容的字符串(在Wordpress中),我想用另一个URL替换图像标签周围的每个链接URL:

Before: <a href="A"><img src="X"></a>
After: <a href="B"><img src="X"></a>

First I wanted to do it with regular expressions, but then I read that this not recommended at all. 首先,我想使用正则表达式来做,但是后来我读到根本不建议这样做。 So is there a possibility to do this with PHP? 那么用PHP可以做到这一点吗?

Use the DOM API 使用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();

Demo ~ https://3v4l.org/ZHTYG 演示〜https ://3v4l.org/ZHTYG

Yes, you can do it easily with DOMDocument : 是的,您可以使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM