Home > Backend Development > PHP Tutorial > Summary and sharing of regular expression methods for processing image addresses and img tags

Summary and sharing of regular expression methods for processing image addresses and img tags

巴扎黑
Release: 2023-03-10 14:58:01
Original
1603 people have browsed it

这篇文章主要介绍了正则表达式处理图片地址、img标签的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

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


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

处理获取到的字符串


<span style="font-size:14px;">//将img标签替换为特定编码方式的表达式 
var reg = /<img[^>]*src[=\"\&#39;\s]+[^\.]*\/([^\.]+)\.[^\"\&#39;]+[\"\&#39;]?[^>]*>/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 = &#39;图片1<img src="arclist/sanai.png">图片2<img src="arclist/em_23.gif">图片3<img src="arclist/451.gif">&#39;; 
   //将img标签替换为特定编码方式的表达式 
   var reg = /<img[^>]*src[=\"\&#39;\s]+[^\.]*\/([^\.]+)\.[^\"\&#39;]+[\"\&#39;]?[^>]*>/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

以上两种方法很好的解决的对img标签的正反运算,第一种方法为之前收集,不记得原作者,如有冒犯可以提出署名。后一种方法为本人自写,存在一定的局限性,欢迎大家讨论~

The above is the detailed content of Summary and sharing of regular expression methods for processing image addresses and img tags. 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