在诸如此类的HTML块中:
<p>Hello: <img src="hello/foo.png" /></p>
我需要将图片的网址src
转换为Laravel storage_path
链接。我正在使用PHP DOMDocument来转换网址,如下所示:
$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
属性的特殊字符?
答案 0 :(得分:1)
您可以使用以下内容:
$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()