我有一些使用空格缩进的多行字符串,我想将其转换为制表符。
将此脚本用于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
个空格,然后替换为{{ 1}}标签。
如果您正在尝试对此进行测试,那么我建议您在控制台中运行它以写入可以在文本编辑器中重新加载的文件以查看选项卡。
0.5x
答案 0 :(得分:2)
您可以使用
preg_replace('~(?:^|\G)\h{2}~m', "\t", $spaces)
请参阅regex demo
<强>详情:
(?:^|\G)
- 行/字符串的开头(^
)或上一次成功匹配的结束(\G
)\h{2}
- 2个水平空格。由于使用m
选项,^
将匹配行的开头,而不仅仅是字符串位置的开头。