需要将非标签自己的空格替换为 &nbsp 例如 有标签时:
            原始: 123  456  <a href="">7 8</a>9 0 <a href="">dd d</a> 
            结果: 123&nbsp456&nbsp <a href="">7&nbsp8</a>9&nbsp0 <a href="">dd&nbspd</a> 
没有标签时:
            原始: 123  456    
            结果:  123&nbsp456&nbsp

解决方案 »

  1.   

    别急,刚回来做好。$html = <<<HTML
    123 456 <a href="">7 8</a>9 0 <a href="">dd d</a>  
    HTML;$pattern = '/([^<]+)(<.*?>)*/';
    $s = preg_replace_callback($pattern, 'foo', $html);
    function foo($matches){
    return str_replace(' ', '&nbsp;', $matches[1]).$matches[2];
    }
    echo $s;
      

  2.   


    谢谢你的回复,这个正在还是有问题  
    例如  <a href="">7 8</a>9 0 <a href="">dd d</a>  111 以链接开头就有问题
      

  3.   


    $html = <<<HTML
    <a href="">7 8</a>9 0 <a href="">dd d</a> 111   
    HTML;$pattern = '/(<.*?>)*([^<]+)(<.*?>)*/';
    $s = preg_replace_callback($pattern, 'foo', $html);
    function foo($matches){
        return $matches[1].str_replace(' ', '&nbsp;', $matches[2]).$matches[3];
    }
    echo $s;
    //<a href="">7&nbsp;8</a>9&nbsp;0&nbsp;<a href="">dd&nbsp;d</a>&nbsp;111&nbsp;&nbsp;&nbsp;