【问题标题】:How to setAttribute of DOMDocument element with special characters?如何使用特殊字符设置 DOMDocument 元素的属性?
【发布时间】:2016-05-11 23:31:03
【问题描述】:

在这样的 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 属性的特殊字符?

【问题讨论】:

  • 你也要关闭这个答案吗?
  • @PedroLobito 如果你的回答是指问题,是的,如果我在任何人回答之前在 SO 上找到一个重复项,我会这样做......这不是预期的吗?
  • 这看起来像 URL 编码。如果 DOMDocument 这样做,我会感到惊讶。是否还有其他可能决定“src”需要进行 url 编码的东西?

标签: php domdocument setattribute


【解决方案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>

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

【讨论】:

猜你喜欢
  • 2011-09-28
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多