VTS Posted June 26, 2006 Share Posted June 26, 2006 Ok, I need to remove whitespace from a text file that I have. I found an expression that will remove the space from the beginning and the end of a string but I need it to change the spaces between my columns in the text file from many spaces to one in addition to removing the spaces before and after the line. Here is an example of what I want it to do:edit** for some reason I cannot put the numbers in the format that they are in the text file. they would have some spaces before the first column then anywhere from 1-9 spaces between the columns.I would like them to have no spaces before the first column or after the last and one space between columns like this:12 3 4 3 4 12 34 1 23 111Thanks in advance for any help I apologize in advance for any stupid questions I ask because I have never used regex before. Quote Link to comment Share on other sites More sharing options...
Wildbug Posted June 26, 2006 Share Posted June 26, 2006 (You need to use the [ code ] [ /code ] tags for preformatted text.)I'd recommend using preg_replace for your situation.[code]preg_replace( array( '/\s{2,}/', '/^\s+/', '/\s+$/' ),array( ' ', '', '' ));[/code]The first regex will replace any instances of two or more ({2,}) whitespace (\s) with a single space.The second regex will remove one or more (+) whitespace characters (\s) from the beginning of a line (^).The third regex will remove one or more (+) whitespace characters (\s) from the end of a line ($). Quote Link to comment Share on other sites More sharing options...
VTS Posted June 26, 2006 Author Share Posted June 26, 2006 Thanks alot wildbug!! I will add that in now. Thanks for explaining the code tag thing too. I didn't know that. Quote Link to comment Share on other sites More sharing options...
Wildbug Posted June 26, 2006 Share Posted June 26, 2006 One other thing: you'll have to put your variables in there, too. I forgot you might not be familiar with [a href=\"http://www.php.net/manual/en/function.preg-replace.php\" target=\"_blank\"]preg_replace()[/a] 's syntax.[b]$new_text[/b] = preg_replace(array('/\s{2,}/','/^\s+/','/\s+$/'),array(' ','',''), [b]$original_text[/b]); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.