$info 是读取的html文件内容,其中有好多标签之间有空格,例如:
nbsp;</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td height="22" ><table width="640" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="22" class="pre_res_titletd"><table width="640" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="10" height="22"> </td> <td width="80" class="pre_res_title_tdn">联系方式</td> <td> </td> <td width="20"></td> </tr> </table></td> </tr> <tr> <td><table width="620" border="0" align="center" cellpadding="0" cellspacing="0"> <tr>如果$info = preg_replace("/\s*/","",$info);可以把里面所有的空格都消除了,当然了标签对里面的空格也没有了,但是我使用$info = preg_replace("/>\s*</","><",$info);就不管用了,所有的空格都消除不了,是我的正则表达式有问题还是对$info的长度有什么限制,该怎么写呢?
nbsp;</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td height="22" ><table width="640" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="22" class="pre_res_titletd"><table width="640" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="10" height="22"> </td> <td width="80" class="pre_res_title_tdn">联系方式</td> <td> </td> <td width="20"></td> </tr> </table></td> </tr> <tr> <td><table width="620" border="0" align="center" cellpadding="0" cellspacing="0"> <tr>如果$info = preg_replace("/\s*/","",$info);可以把里面所有的空格都消除了,当然了标签对里面的空格也没有了,但是我使用$info = preg_replace("/>\s*</","><",$info);就不管用了,所有的空格都消除不了,是我的正则表达式有问题还是对$info的长度有什么限制,该怎么写呢?
nbsp; </td> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td height="22" > <table width="640" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="22" class="pre_res_titletd"> <table width="640" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="10" height="22"> </td> <td width="80" class="pre_res_title_tdn">联系方式 </td> <td> </td> <td width="20"> </td> </tr> </table> </td> </tr> <tr> <td> <table width="620" border="0" align="center" cellpadding="0" cellspacing="0"> <tr>
html;
$str = preg_replace("/(?<=>)\s*(?=<)/",'',$str);
echo htmlspecialchars($str);
这一句正则中(?<=>)是什么意思,有什么作用呢?
所以就应该匹配><中间的\s,而不捕获>和<这两个尖括号。
/(? <=>)\s*(?= <)/
1.(? <=>)\s* : 匹配前面跟着一个>号的\s,不捕获>号
2.\s*(?= <) : 匹配<号前面的\s,不捕获<号本身。连起来就是匹配><之间的空格,不捕获><尖括号。具体去看看正则零宽。