Jump to content


Photo

Removing whitespace....sorry I have never used regex!


  • Please log in to reply
3 replies to this topic

#1 VTS

VTS
  • Members
  • PipPipPip
  • Advanced Member
  • 72 posts
  • LocationTennessee

Posted 26 June 2006 - 05:17 PM

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 1
2 34 1 23 111

Thanks in advance for any help I apologize in advance for any stupid questions I ask because I have never used regex before.

#2 Wildbug

Wildbug
  • Members
  • PipPipPip
  • Advanced Member
  • 1,149 posts

Posted 26 June 2006 - 06:00 PM

(You need to use the [ code ] [ /code ] tags for preformatted text.)

I'd recommend using preg_replace for your situation.

preg_replace(
  array(
    '/\s{2,}/',
    '/^\s+/',
    '/\s+$/'
  ),array(
    ' ',
    '',
    ''
  )
);

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 ($).

Twice a day my clock works PERFECTLY!  I can't figure out what's wrong with it.

#3 VTS

VTS
  • Members
  • PipPipPip
  • Advanced Member
  • 72 posts
  • LocationTennessee

Posted 26 June 2006 - 08:05 PM

Thanks alot wildbug!! I will add that in now. Thanks for explaining the code tag thing too. I didn't know that.

#4 Wildbug

Wildbug
  • Members
  • PipPipPip
  • Advanced Member
  • 1,149 posts

Posted 26 June 2006 - 08:31 PM


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.

$new_text = preg_replace(array('/\s{2,}/','/^\s+/','/\s+$/'),array(' ','',''), $original_text);


Twice a day my clock works PERFECTLY!  I can't figure out what's wrong with it.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users