![](/img/trans.png)
[英]How to get the featured image and put it's image path in to inline styles ie. <div style=“background:url(filepath/here)”;>?
[英]Regex to match url()'s in inline styles <div style=“url()”>
应该在任何地方都可以工作:)
但尤其是那些我觉得棘手的:
<div style="background-image:url('img.png');"></div>
<div style='background-image:url("img.png");'></div>
<div style='background-image:url(img.png);'></div>
<div style='background-image:url(../../img.png);'></div>
<div style='background: #ffffff url( "img.png" ) no-repeat right top;'></div>
注意:应该可以在JavaScript中使用。
如果您想要在每个url(
... )
任何内容
url\(\s*(['"]?)(.*?)\1\s*\)
url # literal characters
\( # escaped left parenthesis to treat it as literal
\s* # 0 or more white-space characters
( # 1st capture group
['"]? # either ' or " or neither
) # end 1st capture group
(.*?) # 2nd (main) capture group, any characters, reluctantly
\1 # back-reference group #1, to ensure that same quote type is used at end
\s* # 0 or more white-space characters
\) # escaped right parenthesis to treat it as literal
http://rubular.com/r/P6FJwxC0L7
如果只在每个url(
... .png)
包含.png文件
url\(\s*(['"]?)(.*?\.png)\1\s*\)
编辑:留出空间,并删除了无用的反向引用
我认为您应该以某种方式获取style
属性的内部文本,然后使用以下正则表达式:
background-image:(?: )*url\((?:'|")?([^'"]*)(?:'|")?\);
唯一匹配的组将是背景图片url的内容,没有可选的前导和/或尾引号( "
或'
)
这应该工作\\\\(['"]?([\\w./]+)
另一种方法是在url(
和可能的空格或引号\\burl\\( *['"]?
之后锚定匹配的开始,并匹配随后的所有内容,直到找到空格,引号或右括号([^'" )]+)
。
var txt='url("/webworks/art/yankee/yankee2.gif")';
var url=(/\burl\( *['"]?([^'" )]+)/.exec(txt)||[])[1];
url>>
/webworks/art/yankee/yankee2.gif
用`||书写 最后的[]``允许不匹配返回未定义而不是抛出错误。
我先按简单的模式/url\\([^(]+\\)/ig
匹配url,然后从结果中删除所有不必要的符号:
var matches = html.match(/url\([^(]+\)/ig);
for(var i = 0; i < matches.length; i++)
// this is a clean url
var url = matches[i].replace(/(^url\s*\(\s*['"]?)|(['"]?\s*\)$)/ig, '');
您可以在jsfiddle上找到完整的代码片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.