Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex suggestion for this task

Status
Not open for further replies.

dspitzle

Programmer
Sep 9, 2003
45
US
I'm trying to figure out a way of using regular expressionsm specifically ereg_replace(), to take an existing string and indent it. Specifically, I'd like to take a string like

line 1\nline 2\nline 3\n

and turn it into

\tline 1\n\tline 2\n\tline 3\n

Note that I don't want a tab after the final \n. Any suggestions on the correct regex?
 
here is a non regex way to do it. did you specifically want regex? and if so, why would you chose ereg over preg?

Code:
function indent(){
 $return = str_replace ("\n", "\n\t", $string);
 if (substr($return, -1) === "\t"){
  $return = substr($return, 0, -1);
 }
 return $return;
}
 
I was hoping that a regular expression would save having to go back and trim the final instance of the inserted tabs. However, your solution might work. One thing I'm trying to figure out though is whether the substr calls in your solution would need to use -2 rather than -1, since "\t" is actually two characters in the strings (even though it gets echoed as a single character).
 
Are you 100% sure about that? The string actually contains the \ character and the t character. I would assume that doing a replace of all t characters or of all \ characters would affect the individual characters.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top