Charles Yeung
Charles Yeung

Reputation: 38803

Using PHP to trim white space/tab for a string

According to the 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,'><'); ?

Upvotes: 1

Views: 303

Answers (2)

Wrikken
Wrikken

Reputation: 70490

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

Upvotes: 4

genesis
genesis

Reputation: 50976

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

Upvotes: 0

Related Questions