简体   繁体   English

正则表达式以查找链接到图像的定位标记

[英]Regex to find anchor tags that link to an image

I'm using this code in my WordPress theme functions.php to add a "fancybox" class to linked images. 我在WordPress主题functions.php中使用此代码向链接的图像添加“ fancybox”类。 However, I do not want to add the fancybox class to images that are linked to non-image URLs. 不过,我希望到的fancybox类添加到链接到非图像的URL图像。

In other words: currently the script will add the "fancybox" class to an HTML structure like this (which I do not want): 换句话说:当前,脚本会将“ fancybox”类添加到这样的HTML结构中(我不希望这样):

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

Where as I only want to add the class to structures like: 我只想将类添加到以下结构中:

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

or 要么

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

How can I modify the regex expression in this code to only include anchor tags whose HREF attribute contains .jpg , .jpeg , .png , or .gif ? 如何在此代码中修改正则表达式,使其仅包含HREF属性包含.jpg.jpeg.png.gif锚标记?

Thank you! 谢谢!

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

The following should work with one caveat. 以下是一个警告。 The link needs to be on a separate line to the image tag, or the file extension of the image will create a match. 链接必须在图像标签的单独一行上,否则图像的文件扩展名将创建一个匹配项。

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

Maybe someone can improve on it rather than posting sarcastic comments :) 也许有人可以改进它,而不是发布讽刺的评论:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM