正则表达式以查找链接到图像的定位标记 [英] Regex to find anchor tags that link to an image
问题描述
我在WordPress主题functions.php中使用此代码向链接的图像添加"fancybox"类.但是,我不想要向链接到非图像URL的图像添加fancybox类.
I'm using this code in my WordPress theme functions.php to add a "fancybox" class to linked images. However, I do not want to add the fancybox class to images that are linked to non-image URLs.
换句话说:当前,脚本会将"fancybox"类添加到这样的HTML结构中(我不想要):
In other words: currently the script will add the "fancybox" class to an HTML structure like this (which I do not want):
< 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>
或
< a href ="http://acme.com/an-image.jpg">< img src ="http://acme.com/another-image.jpg"/></a>
如何在此代码中修改正则表达式,使其仅包含其HREF属性包含 .jpg
, .jpeg
, .png
或 .gif
?
How can I modify the regex expression in this code to only include anchor tags whose HREF attribute contains .jpg
, .jpeg
, .png
, or .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);
推荐答案
以下内容应适用于一个警告.链接必须在图像标签的单独一行上,否则图像的文件扩展名将创建一个匹配项.
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 :)
这篇关于正则表达式以查找链接到图像的定位标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!