$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">&nbsp;</td> <td width="80" class="pre_res_title_tdn">联系方式</td> <td>&nbsp;</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的长度有什么限制,该怎么写呢?

解决方案 »

  1.   

    preg_replace("/>\s*</",'><',$info);
      

  2.   

    发帖的时候$info = preg_replace("/>\s* </","> <",$info);多了一个空格,我自己电脑上试的时候没有那个空格的,楼上的是我这里多了个空格么,我试了不行。
      

  3.   

    echo preg_replace('/>\s*</s', '><', $info);那些可不是空格!
      

  4.   

    不是空格是什么呢?preg_replace('/>\s* </s', '> <', $info); 和preg_replace('/>\s* </', '> <', $info); 多了一个s是什么意思呢?用了preg_replace('/>\s*</s', '><', $info); 这个规则两个标签之间的空白依然存在,
      

  5.   

    $str = <<<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">&nbsp; </td> <td width="80" class="pre_res_title_tdn">联系方式 </td> <td>&nbsp; </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);
      

  6.   

    厉害,问题解决了。但是我还有个疑问$str = preg_replace("/(?<=>)\s*(?=<)/",'',$str);
    这一句正则中(?<=>)是什么意思,有什么作用呢?
      

  7.   

    不能单纯的去替换'/>\s*</'这样一个匹配串,因为>和<也匹配进去了,一起替换掉就不符合你的需求了。
    所以就应该匹配><中间的\s,而不捕获>和<这两个尖括号。
    /(? <=>)\s*(?= <)/
    1.(? <=>)\s* : 匹配前面跟着一个>号的\s,不捕获>号
    2.\s*(?= <)  : 匹配<号前面的\s,不捕获<号本身。连起来就是匹配><之间的空格,不捕获><尖括号。具体去看看正则零宽。
      

  8.   

    正向预查的格式不是(?= )的么?(? <= )这样也可以?是不是把(? <=>)\s*改为.(? <=])\s*就是匹配一个跟着]括号的\s但是不包含]。我猜的对么?