制表符与空格互转
为了对齐,有时需要使用制表符,但是由于不同的浏览器对制表符的设置不同,导致在某些浏览器对齐不成功。
可以通过转换制表符为空格,保证按设置的转换输出。
有时又需要把多个空格合并成制表符,具体成果看代码。
注意:普通输出会把多个空格合并,只有保留格式的输出才能使用。
<?php function pc_tab_expand($text) { while (strstr($text, "\t")) { // 正则表达式第一个子式匹配非\t,后面匹配\t $text=preg_replace_callback('/^([^\t\n]*)(\t+)/m', 'pc_tab_expand_helper', $text); } return $text; } function pc_tab_expand_helper($matches) { // 为表现结果,完整的\t转换为16个空格,可自己设置 $tab_stop=16; // 实际转换的空格数和对应的表项长度有关,如此才可定长整齐排列 return $matches[1].str_repeat(' ', strlen($matches[2]) * $tab_stop - (strlen($matches[1]) % $tab_stop)); } function pc_tab_unexpand($text) { // 参数随上面调整 $tab_stop=16; $lines=explode("\n", $text); foreach ($lines as $i => $line) { // 把所有制表符扩展为空格符 $line=pc_tab_expand($line); $chunks=str_split($line, $tab_stop); $chunkCount=count($chunks); // 扫描除最后一个字符段之外的所有字符段 for ($j=0; $j<$chunkCount-1; $j++) { // 两个空格以上才转换,保留单个的空格 $chunks[$j]=preg_replace('/ {2,}$/', "\t", $chunks[$j]); } // 如果最后一个字符段是相当于一个制表位的空格符 // 将其转换为制表符;否则,不作任何处理 if ($chunks[$chunkCount-1] == str_repeat(' ', $tab_stop)) { $chunks[$chunkCount-1]="\t"; } // 重组所有字段 $lines[$i]=implode('', $chunks); } //重组所有行 return implode("\n", $lines); } $start='<pre>'; $stop='</pre>'; $test="11\t111\t1111\n2222\t222\t22\n33333\t333333\t3333333"; print $start.$test.$stop; $spaced=pc_tab_expand($test); print $start.$spaced.$stop; $unspaced=pc_tab_unexpand($spaced); print $start.$unspaced.$stop;
点赞1
支持一下