根据之前的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,'><');
的语句?
答案 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);