How to setAttribute of DOMDocument element with special characters?
https://stackoverflow.com/questions/37174897/how-to-setattribute-of-domdocument-element-with-special-characters
Ask QuestionAsked 4 years, 11 months agoActive 3 months agoViewed 2k times3
In an HTML block such as this:
<p>Hello: <img src="hello/foo.png" /></p>
I need to transform the URL src
of the image to a Laravel storage_path
link. I'm using PHP DOMDocument to transform the url like so:
$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);
The problem is that the output is src="%7B%7B%20storage_path('app/'%20.%20foo.png)%20%7D%7D"
How can I keep the special characters of the src
attribute?phpdomdocumentsetattributeShareImprove this questionFollowasked May 11 '16 at 23:31greener4,7351010 gold badges4545 silver badges8383 bronze badges
Are you going to close this answer too ? – Pedro Lobito May 11 '16 at 23:32
@PedroLobito if by answer you mean question, yes I would if I find a duplicate on SO before anyone answers.. is that not expected? – greener May 11 '16 at 23:38
That looks like URL encoding. I would be surprised if DOMDocument does this. Is there something else that might decide 'src' needs to be url encoded? – Halcyon May 11 '16 at 23:49
1 Answer
You can use something like:
$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>
Last updated
Was this helpful?