【问题标题】:preg_replace to capture inside Image tagspreg_replace 捕获内部图像标签
【发布时间】:2014-03-11 01:11:56
【问题描述】:

您好,我希望有人可以帮助我解决我遇到的 preg_replace 问题

我有以下preg_replace("/(\/[^\/]*.jpg)/", ".jpg", $input_lines);

想法是将我的 wordpress 站点中的图像替换为其原始名称...该文件已存在于非缓存文件夹中,因此我无需担心该部分...

<img src="http://url.com/wp-content/uploads/cache/2014/02/flag/278439615.jpg">

我有一个替换来处理网址中的cache,所以我留下了这样的网址:

<img src="http://url.com/wp-content/uploads/2014/02/flag/278439615.jpg">

现在下一步是从 URL 中删除 number.jpg,该数字可以是字母或数字。

所有 URL 中的常量是 /.jpg 的最后一次出现,preg_replace("/(\/[^\/]*.jpg)/", ".jpg", $input_lines); 负责

然而问题是 preg_replace 需要在图像标签中查找标签,而不是替换任何不在图像标签中的代码...

如何添加到正则表达式 (preg_replace) 以仅查看图像标签内部的替换?

理想的最终结果是如下所示的 URL:

<img src="http://url.com/wp-content/uploads/2014/02/flag.jpg">

正则表达式 (preg_replace) 还需要替换所有匹配项(页面上可能有多个图像)。

非常感谢您的帮助!

【问题讨论】:

    标签: regex html-parsing preg-replace


    【解决方案1】:

    你可以使用这个替换:

    $pattern = <<<'EOD'
    ~
    <img \s
    (?> [^>s]++ | \Bs | s(?!rc\s*=) )* # possible content before the src attribute 
    src \s* = \s* ["']? [^"\'\s>]+?    # start of the src attribute (until /cache/)
    \K                                 # reset all from match result
    /cache(?=/)
    ([^\s"'>]*?)                       # capture the path before the filename
    /[^\s/]+ (?=\.jpg [>"'\s])         # the filename followed by the .jpg extension
    ~ix
    EOD;
    $result = preg_replace($pattern, '$1', $input_lines);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 2014-09-22
      • 2012-05-17
      • 1970-01-01
      • 2010-10-29
      • 2017-10-04
      相关资源
      最近更新 更多