2015-10-29 112 views
2

我想在括号,单引号和双引号之间提取文本。我已对单引号和双引号,但我不能使它成为第三个参数,括号:php - 在括号,单引号和双引号之间提取文本

例如:

<img src="/path/to/the/file.jpg"></div> 
<img src='/path/to/the/file2.png'></div> 
<div style="background:url(/path/to/the/file555.gif)"></div> 

我想提取:

/path/to/the/file.jpg 
/path/to/the/file2.png 
/path/to/the/file555.gif 

这是我使用正则表达式表达:

preg_match_all('/(["\'])(.*(?:\.jpg|\.png|\.gif))\1/m', $subject, $matches) 

甚至这一个:

preg_match_all('/(["\'])([^"\']*(?:\.jpg|\.png|\.gif))\1/m', $subject, $matches) 

回答

1

可以使用this.See演示。

https://regex101.com/r/cD5jK1/12

$re = "/(?<=['\"\\(])[^\"()\\n']*?(?=[\\)\"'])/m"; 
$str = "<img src=\"/path/to/the/file.jpg\"></div>\n<img src='/path/to/the/file2.png'></div>\n<div style=\"background:url(/path/to/the/file555.gif)\"></div>"; 

preg_match_all($re, $str, $matches); 
+0

存在的问题,此代码在本演示中,你看到的。圆括号之间的文本从'background:...开始'及其前面的双引号 – Afshin

+1

@ AfshinHaghighat检查编辑 – vks

+0

谢谢。它现在有效。我在我的RegexBuddy中检查它,它给我和关于零长度匹配的错误:你的正则表达式可能找到零长度匹配。那是问题吗?! – Afshin

0

您还可以使用正则表达式:

[\"\'\(]+(\/[^\/]+\/[^\/]+\/[^\/]+\/[^\.]+\.(?:jpg|gif|png))[\)\"\']+ 
+1

看起来可怕,你能解释它实际上在做什么? – Martin

+0

我刚刚开始使用\“或\'或\(然后去掉3级,然后转到jpg或gif或png后面的点,以\或\或\)结尾。 –