【问题标题】:php - extract text between parenthesis, single quotes and double quotesphp - 提取括号、单引号和双引号之间的文本
【发布时间】:2015-10-29 10:13:46
【问题描述】:

我想提取括号、单引号和双引号之间的文本。我已经为单引号和双引号做了它,但我不能让它用于第三个参数,括号:

例如:

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

【问题讨论】:

    标签: php regex


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

    【讨论】:

    • 如您所见,此演示中的此代码存在问题。括号之间的文本从background:... 及其前面的双引号开始
    • 谢谢。现在可以了。我在我的 RegexBuddy 中检查它,它给了我关于零长度匹配的错误:您的正则表达式可能会找到零长度匹配。有问题吗?!
    • @AfshinHaghighat 使用 (?&lt;=['"\(])[^"())\n']+?(?=[\)"'])
    • (?&lt;=['"\(])[^"())\n']*(?:\.jpg|\.png|\.gif)(?=[\)"']) 完美运行。
    • 有人不仅对答案投了反对票,还对问题投了反对票:-|
    【解决方案2】:

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

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

    【讨论】:

    • 看起来很可怕,你能解释一下它实际上在做什么吗?
    • 我刚从 \" 或 \' 或 ( 然后转到最多 3 级的斜线,然后转到 jpg 或 gif 或 png 后面的点,并以 \" 或 \' 或 ) .
    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2011-06-02
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多