Adding tabs

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
MathewByrne
Forum Commoner
Posts: 38
Joined: Sat Mar 27, 2004 9:49 pm
Location: Australia

Adding tabs

Post 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.
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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);
Post Reply