Jump to content

Code to remove double spacing??


mikebyrne

Recommended Posts

Im looking to write a piece of code that will remove all the double spacing in my comma separated file and have it as a single space.

 

My file looks like this:

 

,1517,Phxxxips,Txxxxxsa,,4  Gallxxxxshill,Axxxxy,Co.Kxxxxxare

,1517,Phxxxips,Txxxxxsa,,4  Gallxxxxshill,Axxxxy,Co.Kxxxxxare

,1517,Phxxxips,Txxxxxsa,,4  Gallxxxxshill,Axxxxy,Co.Kxxxxxare

 

I would like my output to look like:

 

,1517,Phxxxips,Txxxxxsa,,4 Gallxxxxshill,Axxxxy,Co.Kxxxxxare

 

Any help would be great!

Link to comment
Share on other sites

<?php
$lines = file('yourfile.csv');
$output = "";
foreach($lines as $line) {
$line = str_replace("  ", " ", $line);
$output .= $line;
}
echo $output;
?>

 

You would just need to save $output back out instead of echo

 

that would only replace a maximum of two spaces. what if it were accidentally more than that? the regex would be better

Link to comment
Share on other sites

that would only replace a maximum of two spaces. what if it were accidentally more than that? the regex would be better

The {2} part in the regular expression made it behave the exact same? If it suites his needs then str_replace is way to go (performance wise).

 

As for writing the output to a file you will want to use  file_put_contents() function.

<?php
file_put_contents( 'filename.txt', $contents );
?>

Make sure that if you're using a unix platform that PHP has write permissions on the directory you're trying to write the file to.

Link to comment
Share on other sites

<?php
$lines = file('yourfile.csv');
$output = "";
foreach($lines as $line) {
$line = str_replace("  ", " ", $line);
$output .= $line;
}
echo $output;
?>

 

You would just need to save $output back out instead of echo

 

that would only replace a maximum of two spaces. what if it were accidentally more than that? the regex would be better

 

Yeah, I merely answered his question

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.