如何用小胡子表达式替换img src并在文档中链接href? [英] How to replace img src and link href in a document with a mustache expression?
问题描述
我试图替换 src
, href
值,但是使用 regex
I trying to replace the src
,href
value but with a small modified using regex
简单的例子
//Find:
<img src="icons/google-icon.svg" >
//Replace to:
<img src="{{asset('icons/google-icon.svg')}}" >
//Find:
<link href="css/style.css">
//Replace to:
<link href="{{asset('css/style.css')}}">
/** etc... */
现在这是我的正则表达式:
Now this is my regex:
//Find:
src\s*=\s*"(.+?)"
//Replace to:
src="{{ asset('$1') }}"
它的工作实际上非常好,但是仅用于 src
,而不是[ href
, src
],我也想排除任何值包含 {{asset
And its work very great actually but its only for src
not [href
,src
], also I want to exclude any value that contains {{asset
有什么主意吗?预先感谢
Any idea? Thanks in advance
推荐答案
您可以使用替换来匹配 src
或 href
,然后使用否定的前瞻来断言src/href不是以 {{asset
:
You can use an alternation to match src
or href
, and then a negative lookahead to assert that the src/href doesn't start with {{asset
:
((?:src|href)\s*=\s*")((?!{{\s*asset)[^"]+)
这还将更改< a>
标记或其他地方的 href
属性.如果出现问题,请使用 DOMDocument
一个>解决方案.请注意,如果您的HTML不仅仅是片段,则无需在调用 loadHTML
的过程中在其周围添加 div
标记,最后一行应更改为 echo substr($ doc-> saveXML(),38);
.
This will also change href
attributes inside <a>
tags or elsewhere. If that is an issue, use a DOMDocument
solution instead. Note that if your HTML is not just a snippet then you don't need to add the div
tag around it in the call to loadHTML
and the last line should be changed to echo substr($doc->saveXML(), 38);
.
$html = <<<EOT
//Find:
<img src="icons/google-icon.svg" >
//Replace to:
<img src="{{asset('icons/google-icon.svg')}}" >
//Find:
<link href="css/style.css">
//Replace to:
<link href="{{asset('css/style.css')}}">
/** etc... */
<a href="http://www.example.com">
EOT;
$doc = new DOMDocument();
$doc->loadHTML("<div>$html</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//img') as $img) {
$src = $img->getAttribute('src');
if (preg_match('/^(?!{{\s*asset).*$/', $src, $m)) {
$img->setAttribute('src', "{{asset('" . $m[0] . ")'}}");
}
}
foreach ($xpath->query('//link') as $link) {
$href = $link->getAttribute('href');
if (preg_match('/^(?!{{\s*asset).*$/', $href, $m)) {
$link->setAttribute('href', "{{asset('" . $m[0] . ")'}}");
}
}
// strip XML header and added <div> tag
echo substr($doc->saveXML(), 44, -6);
输出:
//Find:
<img src="{{asset('icons/google-icon.svg)'}}"/>
//Replace to:
<img src="{{asset('icons/google-icon.svg')}}"/>
//Find:
<link href="{{asset('css/style.css)'}}"/>
//Replace to:
<link href="{{asset('css/style.css')}}"/>
/** etc... */
<a href="http://www.example.com"/>
这篇关于如何用小胡子表达式替换img src并在文档中链接href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!