繁体   English   中英

如何使用特殊字符设置 DOMDocument 元素的属性?

[英]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()

暂无
暂无

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

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