2016-09-24 116 views
1

我有一些多行字符串缩进,我想要转换为制表符的空格。如何用换行符替换空格只在换行符上?

拿这个脚本example.php

<?php 

echo <<<EOT 
----------------------------------------------------------------------- 
Example with spaces: 
----------------------------------------------------------------------- 

EOT; 
$spaces = <<<EOD 
For every new line, replace 2 spaces with 1 tab. 
    Here 2 spaces should start with 1 tab. 
Ignore   all spaces  that don't begin on a new line. 
    Now 4 spaces will be 2 tabs. 
This line starts with only 1 space, so it should remain unchanged. 
     And 6 spaces will be 3 tabs. 
Still skipping all spaces that don't begin on a new line. 

EOD; 
echo $spaces; 

$tabs = <<<EOD 
----------------------------------------------------------------------- 
Example replaced with tabs: 
----------------------------------------------------------------------- 
For every new line, replace 2 spaces with 1 tab. 
\tHere 2 spaces should start with 1 tab. 
Ignore   all spaces  that don't begin on a new line. 
\t\tNow 4 spaces will be 2 tabs. 
This line starts with only 1 space, so it should remain unchanged. 
\t\t\tAnd 6 spaces will be 3 tabs. 
Still skipping all spaces that don't begin on a new line. 

EOD; 
echo $tabs; 

我第一次尝试失败:

str_replace(" ", "\t", $spaces); 

这不工作,因为它会与选项卡的线的中间替代多的空间。

我的第二个失败的尝试:

preg_replace("/\n(?=[\h]*[\h])/", "\n\t", $spaces); 

这不工作,因为它只有一个选项卡取代前两个空格。

我觉得我正在寻找某种可变数量的替换函数,或者是一个上下文条件替换,就像在行的开头看到x空格,然后替换为0.5x选项卡。

如果您想要测试这一点,那么我会建议在控制台中运行它以写入文件,您可以在文本编辑器中重新加载以查看选项卡。

php example.php > temp.txt 

回答

2

您可以使用

preg_replace('~(?:^|\G)\h{2}~m', "\t", $spaces) 

regex demo

详细

  • (?:^|\G) - 行/字符串(^)的开始或结束以前的成功匹配(\G
  • \h{2} - 2个水平空格。

由于使用m选项,因此^将匹配行的开始,而不仅仅是字符串位置的开始。

+0

请参阅[在线PHP演示](http://ideone.com/i07WT3)。 –

+1

谢谢!我不知道'\ G',这正是我需要的 –