Page 1 of 1

Adding tabs

Posted: Mon Jun 06, 2005 9:18 am
by MathewByrne
Hi,

I was wondering how I would insert a tab (\t) in before all newline characters (\n) except if the newline comes at the end of a string. Also I'd need to append a \t to the start of the string. For example:

Code: Select all

\t\tSome Text
\tMore text
\t\t\tAlso text
Would become:

Code: Select all

\t\t\tSome Text
\t\tMore text
\t\t\t\tAlso text
I thought about exploding the string, adding the tabs then gluing it back together but I thought there might be a simpler regex way of doing this.

Posted: Mon Jun 06, 2005 11:31 am
by Skara

Code: Select all

preg_replace("/(^|\n)(.+?)/","$1\t$2",$string);
..I think. If that doesn't work, try this:

Code: Select all

preg_replace("/(^|\n)(.+?)(?!$)/","$1\t$2",$string);