您的位置:首页 > 编程语言 > PHP开发

php经典实例中1.7扩展和压缩制表符

2017-09-04 22:16 375 查看
实例1-22中的tab_expand()函数容易理解,就因为没有给例子,压缩让我纠结好久

function tab_expand($text){
//echo strstr($text,"\t");exit;
while(strstr($text,"\t")){
$text = preg_replace_callback('/^([^\t\n]*)(\t+)/m','tab_expand_helper',$text);
}
return $text;
}
function tab_expand_helper($matches){
$tab_stop = 8;
return $matches[1].str_repeat(' ',strlen($matches[2]) * $tab_stop - (strlen($matches[1]) % $tab_stop));
}
function tab_unexpand($text){
$tab_stop = 2;
$lines = explode("\n",$text);
foreach($lines as $i => $line){
$line = 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);
}


测试:



打印结果要复制放到Notepad++查看



上面是处理后的总共27个字符,下面是原版的29个字符

这样依然是对不齐的

将$tab_stop = 4;

再次运行

得到的结果:



会看到处理过的(上)已经对齐了,但是有30个字符,比原先未处理的29多了一个

书中提到的"这样不仅可以保证文本与制表位的对齐,还可以节省字符串空间"

我的理解是:如果原来不经过压缩(替换)处理的字符串要达到对齐的效果,用更多的空格对齐会比被tab_unexpand处理过后的字符串长度还要大,上述书中的原意应该是理解的

理解的误区:认为制表符在同个字符串中"长度"是不可变的(但从截图上来看是可以不一样的)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: