我可以使用哪种正则表达式删除所有带有.jpg扩展名的URL,而让元素代替?

问题描述 投票:0回答:1
我需要使用正则表达式删除所有指向我的wordpress帖子的图像链接。

我将Search Regex插件用于Wordpress。此插件可以在数据库中找到带有正则表达式的内容,并且可以替换它。

一些我需要做的例子:

<a rel="nofollow" href="https://www.exemple.com/test.jpg" class="link" title="test"> <img src="https://www.exemple.com/test.jpg" alt="test"> </a>

to

<img src="https://www.exemple.com/test.jpg" alt="test">

<a href="https://www.exemple.com/test1.png" title="test1" class="link"> <img src="https://www.exemple.com/test1.png" alt="test1"> </a>

to

<img src="https://www.exemple.com/test1.png" alt="test1">

我找到了一些正则表达式解决方案,例如:https://regex101.com/r/xX9pJ8/1或这里https://stackoverflow.com/a/40292492/2831419,但我无法使其适应我的需要。如果您有解决方案,请让我知道,谢谢
php regex wordpress hyperlink jpeg
1个回答
0
投票
正如其他人提到的:

我的第一点就是regular expressions may well not be the path you want to take in this case

您最好进行一些设置以解析帖子的HTML,找到包含图像标签的锚标签,然后检查图像标签源属性以查看扩展名是否以“ jpg”结尾,如果是,则替换锚标签和图片标签。


此外,使用WordPress会使难度增加一些,并且[[可以完成。请注意,正如您可以在链接中看到的那样,这不是RegEx的目的,它不能处理所有单个情况。无论如何,this is the expression我想出了:(是的,不简洁,因为这不是最佳用法)

/<a[^>]+href ?= ?["'][^"']+\.(?:jpe?g|png)["'].+\n?\r?[\s]{0,100}<img[^>]+= ?["']([^"']+\.(?:jpe?g|png))["'].+\n?\r?[\s]{0,100}<\/a>/gim 这可用于PCRE或JS,适用于png,PNG,jpg,JPG,jpeg和JPEG。如果您愿意,这是一个解释:

/<a[^>]+href ?= ?["'][^"']+\.(?:jpe?g|png)["']     This matches the anchor tag
  .+\n?\r?                                         This accounts for line breaks
    [\s]{0,100}                                    This accounts for white space
      <img[^>]+= ?["']([^"']+\.(?:jpe?g|png))["']  This matches the image tag, and saves the link
    .+\n?\r?[\s]{0,100}<\/a>                       This matches the closing tag, for a clean replace
/gim                                               Global, Case-Insensitive, Multi-Line

然后您将整个搜索替换为:<img src="$1">

© www.soinside.com 2019 - 2024. All rights reserved.