【问题标题】:Regex to find anchor tags that link to an image正则表达式查找链接到图像的锚标签
【发布时间】:2016-07-24 19:39:50
【问题描述】:

我在我的 WordPress 主题 functions.php 中使用此代码向链接图像添加“fancybox”类。但是,我不想将 fancybox 类添加到链接到非图像 URL 的图像中。

换句话说:目前脚本会将“fancybox”类添加到这样的 HTML 结构中(我不想要):

<a href="http://acme.com/a-non-image-link"> <img src="http://acme.com/image.jpg" /> </a>

我只想将类添加到以下结构中:

<a href="http://acme.com/an-image.jpg"> <img src="http://acme.com/an-image.jpg" /> </a>

<a href="http://acme.com/an-image.jpg"> <img src="http://acme.com/another-image.jpg" /> </a>

如何修改此代码中的正则表达式以仅包含其 HREF 属性包含 .jpg.jpeg.png.gif 的锚标记?

谢谢!

        // Add fancybox class to linked images
        function add_classes_to_linked_images($html) {
            $classes = 'fancybox fancybox-img'; // can do multiple classes, separate with space

            $patterns = array();
            $replacements = array();

            $patterns[0] = '/<a(?![^>]*class)([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor tag where anchor has no existing classes
            $replacements[0] = '<a\1 class="' . $classes . '"><img\2><span class="post-content-fb-btn"></span></a>';

            $patterns[1] = '/<a([^>]*)class="([^"]*)"([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in double quotes
            $replacements[1] = '<a\1class="' . $classes . ' \2"\3><img\4> <span class="post-content-fb-btn"></span></a>';

            $patterns[2] = '/<a([^>]*)class=\'([^\']*)\'([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in single quotes
            $replacements[2] = '<a\1class="' . $classes . ' \2"\3><img\4> <span class="post-content-fb-btn"></span></a>';

            $html = preg_replace($patterns, $replacements, $html);

            return $html;
        }

        add_filter('the_content', 'add_classes_to_linked_images', 100, 1);

【问题讨论】:

标签: php regex wordpress fancybox


【解决方案1】:

以下内容应该有一个警告。该链接需要位于图片标签的单独行上,否则图片的文件扩展名将创建匹配项。

/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i

也许有人可以改进它而不是发布讽刺的 cmets :)

【讨论】:

  • 如果 URL 根本没有扩展名,这似乎会中断。你知道如何纠正吗? &lt;a href="/work/artwork"&gt; 不应该匹配,但仍然是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多