如何设置具有特殊字符的DOMDocument元素的Attribute


How to setAttribute of DOMDocument element with special characters?

在这样的HTML块中:

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

我需要将图像的URL src转换为Laravel storage_path链接。我使用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()