php 匹配img标签,php – 正则表达式匹配图像但不在img标签内

我有一个函数将所有外部图像链接转换为字符串中的img标记.

它运作良好但也匹配< img>内的链接标签

例如:

$text = '

lorem ipsum http://example.jpg example.jpg

';

echo make_clickable($text);

function make_clickable($text) {

$replace = '

%240

';

$text = preg_replace('~https?://[^/\s]+/\S+\.(jpg|png|gif)~i', $replace, $text );

return $text;

}

此测试也将匹配纯文本和src.

有没有办法排除img标签?

解决方法:

你可以使用一些非常有名的正则表达式:

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

让我们解释一下模式:

[^>]* # 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 :)

我们的想法是匹配img标签并跳过它,同时匹配所有这些URI.

标签:html,php,regex

来源: https://codeday.me/bug/20191003/1846897.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值