使用PHP修剪字符串的空格/制表符

时间:2011-08-02 01:21:51

标签: php

根据之前的topic,我将修改PHP中的字符串的空格/制表符。

$html = '<tr>       <td>A     </td>                <td>B   </td>      <td>C    </td>       </tr>'

转换为

$html = '<tr><td>A     </td><td>B   </td><td>C    </td></tr>'

如何撰写喜欢str.replace(/>\s+</g,'><');的语句?

2 个答案:

答案 0 :(得分:4)

$str = preg_replace('/(?<=>)\s+(?=<)/', '', $str);

不易破损,但使用更多资源:

<?php
$html = '<tr>       <td>A     </td>                <td>B   </td>      <td>C    </td>       </tr>';
$d = new DOMDocument();
$d->loadHTML($html);
$x = new DOMXPath($d);
foreach($x->query('//text()[normalize-space()=""]') as $textnode){
    $textnode->deleteData(0,strlen($textnode->wholeText));
}
echo $d->saveXML($d->documentElement->firstChild->firstChild);

答案 1 :(得分:0)

http://sandbox.phpcode.eu/g/54ba6.php

结果

<tr><td>A     </td><td>B   </td><td>C    </td></tr>

<?php 
$html = '<tr>       <td>A     </td>                <td>B   </td>      <td>C    </td>       </tr>'; 
$html = preg_replace('~(</td>)([\s]+)(<td>)~', '$1$3', $html); 
$html = preg_replace('~(<tr>)([\s]+)(<td>)~', '$1$3', $html); 
echo preg_replace('~(</td>)([\s]+)(</tr>)~', '$1$3', $html);