开发者

Using PHP to trim white space/tab for a string

According to t开发者_运维技巧he previous topic, I am going to trim white space/tab for a string in PHP.

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

converting to

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

How to write the statement likes str.replace(/>\s+</g,'><'); ?


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

Less prone to breakage, but uses some more resources:

<?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);


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

result

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

code

<?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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜