【正则】解决小于号(<)大于号(>)引起的浏览器解析成残缺html标记引起的浏览器显示错误

通常小于号(<)大于号(>)在浏览器直接输出可能会被浏览器解析成残缺html标记,从而引起的浏览器排版显示错误,甚至页面空白,

这时候我们就要对小于号(<)大于号(>)做特殊处理了,把单只的小于号(<)大于号(>)进行HTML编码为 &lt; 和 &gt;

下面就是php进行正则处理:

<?php
header("Content-type: text/html; charset=utf-8");
$html = "2||||||3=55||||||1*3/2,5>N,3<N<5? <video width='550' height='400' controls='controls'>
<source src='/flashPlayer/transCode.php?playvideo=Iz49OH1panV6cG9xCQYTDxULCw0NDgUEAx1jVVxBWF5ITwZFVxIKExYXFxJ%2BL3kpI3guKHR0dHYiIXByOzZoP2o5PD82Mz0qbnI1S0k%3D' 
 type='video/mp4'>Do not recognize the video tag, please switch to IE11 kernel. <br>If no support IE11, <a href='https://support.microsoft.com/zh-cn/help/18520/download-internet-explorer-11-offline-installer?target=IE&test.ppt' style='text-decoration:underline'> 
</video>

<p class='color:red'>aaaa <a href='###'>test</a> i<n 
 <video />
 <video id='mm' />
 <video width='550' height='400' controls='controls'
 id='xxx'>
 k>x
 add
</p>
";

//【正则】解决小于号(<)大于号(>)引起的浏览器解析成残缺html标记引起的浏览器显示错误

//$str = str_replace(array("<",">",chr(30),chr(31)),array("&lt;","&gt;","<",">"), preg_replace('#<(/?\w+)([^\>]*?)>#im', chr(30).'\\1\\2'.chr(31), $html));
//$str = preg_replace('#&lt;(.*?)&gt;#im', '<\1>', str_replace(array("<",">"),array("&lt;","&gt;"),$html));

//$str = str_replace(array("<",">",chr(30),chr(31)),array("&lt;","&gt;","<",">"), preg_replace('#<((/?\w+)([^\>]*?)\n*)>#ims', chr(30).'\\1'.chr(31), $html));
//#或者:
$str = preg_replace('#&lt;((/?\w+)((?!&lt;).)*?\n*)&gt;#ims', '<\1>', str_replace(array("<",">"),array("&lt;","&gt;"),$html));
echo $str;

//总结:
//排除(不匹配)某个字符:  [^\>]*?
//排除(不匹配)某串字符:  ((?!&lt;).)*?
//加修饰符s可匹配多行换行符\n

掌握好正则,能事半功倍。

posted @ 2020-12-17 08:58  php学习笔记  阅读(1338)  评论(0编辑  收藏  举报