[英]Regex to find anchor tags that link to an image
我在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);
以下是一个警告。 链接必须在图像标签的单独一行上,否则图像的文件扩展名将创建一个匹配项。
/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i
也许有人可以改进它,而不是发布讽刺的评论:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.