正则表达式匹配图像,但不在img标签内 [英] Regex match images but not inside img tag

查看:99
本文介绍了正则表达式匹配图像,但不在img标签内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数将所有外部图像链接转换为字符串中的img标签。
它运作良好,但也匹配< img> 标记



中的链接,例如:

  $ text ='< p> lorem ipsum http://example.jpg< img src =example.jpg> ;< / p为H.'; 
echo make_clickable($ text);

函数make_clickable($ text){
$ replace ='< p class =update-image>< a href =$ 0target =_ blank> < img src =$ 0>< / a>< / p>';
$ text = preg_replace('〜https?:// [^ / \s] + / \ S + \。(jpg | png | gif)〜i',$ replace,$ text);
返回$ text;
}

此测试将匹配纯文本和 src 也是。
有没有办法排除 img 标签?

>您可以使用一些非知名的正则表达式功能:

 < img [^>]>(* SKIP)(* FAIL)| https::// [^ / \s] + / \ S + \。(?:jpg | png | gif)



$ b

让我们来解释一下模式:

 < img#匹配文字< img 
[^>] *#匹配除>零次或多次
> #匹配文字>
(* SKIP)(* FAIL)#使其失败
| #或
https? #匹配http或https
://#匹配文字://
[^ / \s] +#匹配除空格和正斜杠之外的任何内容一次或多次
/ #匹配文字/
\S +#匹配一个或多个非空白区域
\。 #匹配字面点
(?:jpe?g | png | gif)#匹配jpg,jpeg,png,gif
#不要忘记设置i修饰符:)

这个想法是匹配 img 标签并跳过它,同时匹配所有这些URI。



Online演示


I have a function which converts all external image links into img tags in a string. It works well but also matches links inside <img> tag

for example:

$text = '<p>lorem ipsum http://example.jpg <img src="example.jpg"></p>';
echo make_clickable($text);

function make_clickable($text) {
    $replace = '<p class="update-image"><a href="$0" target="_blank"><img src="$0"></a></p>';
    $text = preg_replace('~https?://[^/\s]+/\S+\.(jpg|png|gif)~i', $replace, $text );
    return $text;
}

this test will match both, plain text and src too. it there a way to exclude img tag?

解决方案

You may use some non-well-known regex power:

<img[^>]*>(*SKIP)(*FAIL)|https?://[^/\s]+/\S+\.(?:jpg|png|gif)

Let's explain the pattern a bit:

<img                # match a literal <img
[^>]*               # match anything except > zero or more times
>                   # match a literal >
(*SKIP)(*FAIL)      # make it fail
|                   # or
https?              # match http or https
://                 # match a literal ://
[^/\s]+             # match anything except white-space and forward slash one or more times
/                   # match a literal /
\S+                 # match a non-white-space one or more times
\.                  # match a literal dot
(?:jpe?g|png|gif)   # match jpg, jpeg, png, gif
                    # Don't forget to set the i modifier :)

The idea is to match the img tag and skip it, meanwhile match all those URI's.

Online demo

这篇关于正则表达式匹配图像,但不在img标签内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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