簡體   English   中英

如何僅在換行符上用制表符替換空格?

[英]How to replace spaces with tabs only on a newline?

我有一些多行字符串,其中包含要轉換為制表符的空格。

把這個腳本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

您可以使用

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

正則表達式演示

詳細資料

  • (?:^|\\G) -行/字符串的開頭( ^ )或上一個成功匹配項的結尾( \\G
  • \\h{2} -2個水平空白。

由於使用了m選項,因此^將匹配行的開頭,而不僅僅是字符串位置的開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM