background image

PHP 中扩展和压缩制表符

在 PHP 中你可以把字符串中的空格符变成制表符(或相反),直到文本与制表位对齐。

例如,你想以标准的方式向用户显示格式化以后的文本内容。这时候我们可以使用
str_replace()把空格符替换成制表符,或者把制表符替换成空格符,如下面的例子所示:

<?php
$r= mysql_query("SELECT message FROM messages WHERE id = 1")ordie();
$ob= mysql_fetch_object($r);
$tabbed=str_replace(' ',"\t",$ob->message);
$spaced=str_replace("\t",' ',$ob->message);
print"With Tabs: <pre>$tabbed</pre>";
print"With Spaces: <pre>$spaced</pre>";
?>

但是,使用 str_replace()进行转换没有考虑到制表位的问题。如果你想要每八个字符设

置一个制表位,那么对于以一个五个字母的单词和一个制表符开头的一行文本,这个制
表符就要用三个空格符来替换,而不是一个。使用下例中的 pc_tab_ expand()函数,可以在

 

考虑制表位的前提下把制表符转换为空格符。

<?php
functionpc_tab_expand($text) {
while(strstr($text,"\t")) {
$text= preg_replace_callback('/^([^\t\n]*)(\t+)/m','pc_tab_expand_helper',$text);
}
return$text;
}
functionpc_tab_expand_helper($matches) {
$tab_stop= 8;
return$matches[1] .
str_repeat(' ',strlen($matches[2]) *
$tab_stop- (strlen($matches[1]) %$tab_stop));
}
$spaced= pc_tab_expand($ob->message);
?>

可以使用下例中的 pc_tab_ unexpand()

 

函数把空格符转换回制表符。

<?php
functionpc_tab_unexpand($text) {
$tab_stop= 8;
$lines=explode("\n",$text);
foreach($linesas$i=>$line) {
// Expand any tabs to spaces
$line= pc_tab_expand($line);
$chunks=str_split($line,$tab_stop);
$chunkCount=count($chunks);