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.
Link to comment
Share on other sites

(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 ($).
Link to comment
Share on other sites


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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.