如何设置具有特殊字符的 DOMDocument 元素的属性?

How to setAttribute of DOMDocument element with special characters?

在这样的 HTML 块中:

<p>Hello: <img src="hello/foo.png" /></p>

我需要将图像的 URL src 转换为 Laravel storage_path link。我正在使用 PHP DOMDocument 像这样转换 url:

$link = $a->getAttribute('src');
$pat = '#(\w+\.\w+)+(?!.*(\w+)(\.\w+)+)#';
$matches = [];
preg_match($pat, $link, $matches);
$newStr = "{{ storage_path('app/' . " . $matches[0] . ") }}";
$a->setAttribute('src', $newStr);

问题是输出是src="%7B%7B%20storage_path('app/'%20.%20foo.png)%20%7D%7D"

如何保留 src 属性的特殊字符?

您可以使用类似的东西:

$html = '<p>Hello: <img src="hello/foo.png" /></p>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$img = $dom->getElementsByTagName('img');
$img->item(0)->setAttribute('src', '{{ storage_path(\'app/\' . foo.png) }}');
#loadHTML causes a !DOCTYPE tag to be added, so remove it:
$dom->removeChild($dom->firstChild);
#it also wraps the code in <html><body></body></html>, so remove that:
$dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);
$newImage = urldecode($dom->saveHTML());
//<p>Hello: <img src="{{ storage_path('app/' . foo.png) }}"></p>

注: 为了根据需要输出 img src ,您需要使用 urldecode()