简体   繁体   English

检测图像URL并包装IMG标签?

[英]Detect image URL and wrap in IMG tags?

Trying to hack away at a Wordpress installation to add a little more user-friendliness in the comment section of a specific plugin. 尝试破解Wordpress安装,以在特定插件的注释部分添加更多的用户友好性。

Given three cases: 给定三种情况:

1 1

This is a sentence and image on a newline
http://imgur.com/image.gif

2 2

This is a sentence http://imgur.com/image.gif

3 3

This is a sentence and an image with IMG tags entered by user already
<img src="This is a sentence http://imgur.com/image.gif" alt="" />

When displaying these three types of comments from a user, I'd like to have PHP detect the 1st case and 1st case only - an image url on a newline (a URL that ends in common image extensions) and simply wrap it in <img> tags when displaying. 当显示用户的这三种类型的注释时,我想让PHP仅检测第一种情况和第一种情况-换行符上的图像URL(以常见图像扩展名结尾的URL)并将其包装在<img>显示时的标签。

The part I'm having trouble with, given the string of the comment, how does PHP accurate detect an image link like that? 给定注释字符串,我遇到的问题是PHP如何准确地检测到这样的图像链接?

I feel like this could be accomplished with regex but I've never been terribly skilled with it? 我觉得这可以用正则表达式来完成,但是我从来没有熟练过它吗? Or is it more complicated? 还是更复杂?

You can use this regex will will look at the start of each line ( (?m)^ ), any amount of horizontal whitespace ( \\h* ) (spaces or tabs), and then the HTTP protocol ( https?:// ). 您可以使用此正则表达式查看每行的开头( (?m)^ ),任意数量的水平空白( \\h* )(空格或制表符),然后https?:// HTTP协议( https?:// ) 。 After the protocol it takes any non-space characters ( \\S+? ) (because URLs can't have spaces) until the allowed extension ( jpe?g|gif|png|tiff|svg ). 协议之后,它将接受任何非空格字符( \\S+? )(因为URL不能包含空格),直到允许的扩展名( jpe?g|gif|png|tiff|svg )。

(?m)^\h*(https?://?\S+?\.(?:jpe?g|gif|png|tiff|svg))

Replace with: 用。。。来代替:

<img src="$1" />

https://regex101.com/r/OXvsBl/3/ https://regex101.com/r/OXvsBl/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM