Home > Web Front-end > JS Tutorial > body text

How to match image address and img tag with regular expression

php中世界最好的语言
Release: 2018-03-29 15:51:45
Original
6309 people have browsed it

这次给大家带来正则表达式怎么匹配图片地址与img标签的,正则表达式匹配图片地址与img标签的注意事项有哪些,下面就是实战案例,一起来看一下。

再上传表情或者图片地址时候很多时候不能直接上传<img src=" " />,因此在上传评论或者图片之前应该先处理一下img标签。举例如下,希望可以帮助更多的程序猿~

<span style="font-size:14px;">//第一步是获取到带有img标签的字符串 
var str = '图片1<img src="arclist/sanai.png">图片2<img src="arclist/em_23.gif">图片3<img src="arclist/451.gif">';</span>
Copy after login

处理获取到的字符串

<span style="font-size:14px;">//将img标签替换为特定编码方式的表达式 
var reg = /<img[^>]*src[=\"\'\s]+[^\.]*\/([^\.]+)\.[^\"\']+[\"\']?[^>]*>/gi; 
str = str.replace(reg, "[face:$1.gif]"); 
console.log(str);</span>
Copy after login

运算结果为:

<span style="font-size:14px;">图片1[face:sanai.gif]图片2[face:em_23.gif]图片3[face:451.gif]</span>
Copy after login

这样上传到服务器的代码就不会存在html标签,这是一种很好的应对带有图片评论且上传信息禁止html标签的方法。

接下来:

从服务器上返回的上一步中的运行结果,在反向解析,方法如下:

<span style="font-size:14px;">//将特定编码方式替换成img标签的表达式 
var regg = /
face:([\w]+).gif
/gi; 
str = str.replace(regg,"<img src=&#39;images/$1.gif&#39; />"); 
console.log(str);</span>
Copy after login

运行结果为:

<span style="font-size:14px;">图片1<img src=&#39;images/sanai.gif&#39; />图片2<img src=&#39;images/em_23.gif&#39; />图片3<img src=&#39;images/451.gif&#39; /></span>
Copy after login

下面附上代码的html页,可以全部复制粘贴到html文件中直接运行,亲测可用

<span style="font-size:14px;"><!DOCTYPE html> 
<html> 
 <head> 
  <meta charset="UTF-8"> 
  <title></title> 
 </head> 
 <body> 
  <script> 
   var str = '图片1<img src="arclist/sanai.png">图片2<img src="arclist/em_23.gif">图片3<img src="arclist/451.gif">'; 
   //将img标签替换为特定编码方式的表达式 
   var reg = /<img[^>]*src[=\"\'\s]+[^\.]*\/([^\.]+)\.[^\"\']+[\"\']?[^>]*>/gi; 
   str = str.replace(reg, "[face:$1.gif]"); 
   console.log(str); 
   //将特定编码方式替换成img标签的表达式 
   var regg = /
face:([\w]+).gif
/gi; 
   str = str.replace(regg,"<img src=&#39;images/$1.gif&#39; />"); 
   console.log(str); 
  </script> 
 </body> 
</html></span>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

正则表达式的模糊匹配功能如何实现

验证用户名与密码的15个正则

完全匹配数字与字母密码的正则(步骤详解)

The above is the detailed content of How to match image address and img tag with regular expression. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!