php - 在括号,单引号和双引号之间提取文本

时间:2015-10-29 10:13:46

标签: php regex

我想在括号,单引号和双引号之间提取文本。我已经为单引号和双引号创建了它,但是我不能将它用于第三个参数,括号:

例如:

<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)

2 个答案:

答案 0 :(得分:1)

(?<=['"\(])[^"())\n']*?(?=[\)"'])

你可以使用它。参见演示。

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);

答案 1 :(得分:0)

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

[\"\'\(]+(\/[^\/]+\/[^\/]+\/[^\/]+\/[^\.]+\.(?:jpg|gif|png))[\)\"\']+
相关问题