我正在寻找将一行开头的4个空格替换为标签,但没有任何进一步的文本存在。使用标签替换空间缩进
为了便于阅读,我的初始正则表达式为/ {4}+/
或/[ ]{4}+/
,但显然任何带有四个空格的实例都将被替换。
$string = ' this is some text --> <-- are these tabs or spaces?';
$string .= "\n and this is another line singly indented";
// I wrote 4 spaces, a tab, then 4 spaces here but unfortunately it will not display
$string .= "\n \t and this is third line with tabs and spaces";
$pattern = '/[ ]{4}+/';
$replace = "\t";
$new_str = preg_replace($pattern , $replace , $string);
echo '<pre>'. $new_str .'</pre>';
这是什么,我原本使用给出的表达问候的转换,但一个事实,完美的作品正则表达式的例子是,之间的4个空格----> ---- <被一个标签取代。我真的很希望压缩后的文本保持不变。
我最大的努力迄今已(^
)线的起点([ ]{4}+
)模式(.*?[;\s]*
)任何东西直到第一个非空间\s
$pattern = '/^[ ]{4}+.*?[;\s]*/m';
这......几乎工程,但对于事实上,缩进现在已经失去了,任何人都可以帮助我理解我在这里失去了什么?
[编辑]
为清楚什么,我试图做的是改变从空间到标签的文本缩进的开始,我真的不明白为什么这是混乱的人。
要尽可能明确(使用上面的$string
值):
First line has 8 spaces at the start, some text with 4 spaces in the middle.
I am looking for 2 tabs at the start and no change to spaces in the text.
Second line has 4 spaces at the start.
I am looking to have only 1 tab at the start of the line.
Third line has 4 spaces, 1 tab and 4 spaces.
I am looking to have 3 tabs at the start of the line.
我可能失去了一些东西。你的问题只有一个标签更换四个空格,或者是 – Niitaku
尝试'preg_replace('〜(?:^ | \ G)[] {4}〜m',“\ t”,$ s)',请参阅https://ideone.com/EzjRYC。 –
@WiktorStribiżew这仍然没有解决第三行中间有一个标签 – Lucas