如何添加rel =&"lightbox&"仅链接到包含图像的链接,而不链接到其余的链接? [英] How to add rel="lightbox" only to links which are including an image and not the rest of the links?

查看:56
本文介绍了如何添加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>

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

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

到这里没事,但是其余不包含任何照片的a 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 ...>后跟

Using a lookahead to check, if the <a ...> is followed by <img

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

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