我正在尋找將一行開頭的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