Jump to content

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


VTS

Recommended Posts

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

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]);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.