Just a Simple Quick Question.
I want to replace the Double Spaces at the begenning of the line by Tabs.
Currently I am trying with preg_replace('~^( {2})~', "\t", $text)
but that replaces only the first occurrence of Double Space.
--EDIT--
preg_replace('~PATTERN~', "REPLACEMENT", " HalloWorld")
//Should be equal to "\t\t\tHallo World"
From another questions answer: https://stackoverflow.com/a/4349514/778669
If it is for XML from a DOMDocument which uses 2 spaces to indent:
Will replace every double space indent at the start of the line with a tab.
So the result would be (substituting X for tab):
And the double spaces inside the xml will be left intact.
If you want to replace more than one occurrence of double-spaces with tabs, try this:
If your text is multiline, add the
m
modifier to your regex so it considers^
as the start boundary after a newline character (for each line in your string):I found a solution without PREG functions.
Let us say we have a
$str = " My Text";
I needed an aux variable to store an integer:
The PREG function is more elegant, but I'm not sure of how efficient it is
You can use \G escape sequence for that:
\G marks the location of the end of the previous match (or the beginning of the string for the first match); that way, all matches after the first one try to consume additional two spaces from the character previous match left off.
Testing and wortking:
Edit
Felix has the force with this one!
Proper solution
Replace first 2 spaces on the line
^ {2}
and then every two spaces that follow the last successful replacement\G {2}
.\G
is last replacement and/S
is optimized replace as we are going to replace more occurrences at once and/m
treat it as multi-line string.At the end it will ignore all spaces if they are not at the beginning of the line which I understood was the point, right?