【正则】解决小于号(<)大于号(>)引起的浏览器解析成残缺html标记引起的浏览器显示错误
通常小于号(<)大于号(>)在浏览器直接输出可能会被浏览器解析成残缺html标记,从而引起的浏览器排版显示错误,甚至页面空白,
这时候我们就要对小于号(<)大于号(>)做特殊处理了,把单只的小于号(<)大于号(>)进行HTML编码为 < 和 >
下面就是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("<",">","<",">"), preg_replace('#<(/?\w+)([^\>]*?)>#im', chr(30).'\\1\\2'.chr(31), $html)); //$str = preg_replace('#<(.*?)>#im', '<\1>', str_replace(array("<",">"),array("<",">"),$html)); //$str = str_replace(array("<",">",chr(30),chr(31)),array("<",">","<",">"), preg_replace('#<((/?\w+)([^\>]*?)\n*)>#ims', chr(30).'\\1'.chr(31), $html)); //#或者: $str = preg_replace('#<((/?\w+)((?!<).)*?\n*)>#ims', '<\1>', str_replace(array("<",">"),array("<",">"),$html)); echo $str; //总结: //排除(不匹配)某个字符: [^\>]*? //排除(不匹配)某串字符: ((?!<).)*? //加修饰符s可匹配多行换行符\n
掌握好正则,能事半功倍。