[英]How to replace spaces with tabs only on a newline?
I have some multi-line strings that are indented with spaces that I would like to convert to tabs. 我有一些多行字符串,其中包含要转换为制表符的空格。
Take this script for example.php
把这个脚本
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;
My first failed attempt: 我的第一次失败尝试:
str_replace(" ", "\t", $spaces);
This doesn't work because it will replace multi-spaces in the middle of a line with tabs. 这是行不通的,因为它将用制表符替换一行中间的多个空格。
My second failed attempt: 我第二次失败的尝试:
preg_replace("/\n(?=[\h]*[\h])/", "\n\t", $spaces);
This doesn't work because it only replaces the first two spaces with a tab. 这是行不通的,因为它仅用制表符替换了前两个空格。
I feel like I'm looking for some sort of variable number of replacements function, or a contextually conditional replacement, like if you see x
spaces at the beginning of a line, then replace with 0.5x
tabs. 我觉得我正在寻找某种数量可变的替换函数,或者是上下文条件替换,例如如果您在一行的开头看到
x
空格,然后用0.5x
制表符替换。
If you're trying to test this out, then I would suggest running it in a console to write to a file that you can reload in a text editor to view the tabs. 如果您要进行测试,则建议您在控制台中运行它以写入文件,然后可以在文本编辑器中重新加载该文件以查看选项卡。
php example.php > temp.txt
You may use 您可以使用
preg_replace('~(?:^|\G)\h{2}~m', "\t", $spaces)
See the regex demo 见正则表达式演示
Details : 详细资料 :
(?:^|\\G)
- the beginning of a line/string ( ^
) or the end of the previous successful match ( \\G
) (?:^|\\G)
-行/字符串的开头( ^
)或上一个成功匹配项的结尾( \\G
) \\h{2}
- 2 horizontal whitespaces. \\h{2}
-2个水平空白。 Since the m
option is used, ^
will match start of lines, not just the start of string position. 由于使用了
m
选项,因此^
将匹配行的开头,而不仅仅是字符串位置的开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.