我有一个函数将所有外部图像链接转换为字符串中的img标记.
它运作良好但也匹配< img>内的链接标签
例如:
$text = '
lorem ipsum http://example.jpg
echo make_clickable($text);
function make_clickable($text) {
$replace = '
';$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