2016-09-24 175 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',這正是我需要的 –