如何添加rel =" lightbox"仅限于包含图片而非其他链接的链接? [英] How to add rel="lightbox" only to links which are including an image and not the rest of the links?

查看:139
本文介绍了如何添加rel =" lightbox"仅限于包含图片而非其他链接的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说(在php中)我们有一个包含文本,链接和图像的变量:

Lets say that (in php) we have a variable which has text, links and images :

<a href="myimage_big"><img src="myimage.jpg" alt="pic" title="pic" border="0" /></a>

我们想在每个href标签中添加rel =light,如下所示:

and we want to add to every a href tag the rel="light" as follow :

<a rel="lightbox" href="myimage_big"><img src="myimage.jpg" alt="pic" title="pic" border="0" /></a>

如果变量的名称可以说是 $ mydata 那么使用str_replace我们可以按照以下方式解决我们的问题:

If the name of the variable is lets say $mydata then with str_replace we can do as follow to solve our problem :

$mydata = str_replace('<img ', '<img rel="lightbox"', $mydata);

直到这里没事,但其余的href链接不包括任何内容照片:

Till here is all right, but what about the rest of the a href links that are not including any photo :

例如,

<a href="link1.php">link_no1</a>
<a href="link2.php">link_no2</a>

等?对于这种不包含任何图像的链接,但是使用我们的str_replace代码的文本也会有一个不正确的rel =lightbox属性,我不想要:

etc ? To this kind of links that are not including any image but text then with our str_replace code will also have a rel="lightbox" attribute that is not correct and i dont want :

<a rel="lightbox" href="link1.php">link_no1</a>

那么我们如何才能将rel =lightbox应用于包含一些图像的链接以及那些不包含任何图像的链接都不设置rel =lightbox属性..!?

So how we can apply the rel="lightbox" only to the links that are including some image and to those links that are not including any image to dont set the rel="lightbox" attribute ..!?

推荐答案

这个正则表达式是否解决了这个问题?

Does this regex solve the problem?

$str = '<a href="myimage_big"><img src="myimage.jpg" /></a>';

$str = preg_replace('~<a(?=[^>]+>\s*<img)~','<a rel="lightbox"',$str);

echo htmlspecialchars($str);

使用预测,如果< a ...> 后跟< img

这篇关于如何添加rel =&quot; lightbox&quot;仅限于包含图片而非其他链接的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆