繁体   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