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
https://forums.phpfreaks.com/topic/152989-code-to-remove-double-spacing/
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

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.

<?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

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.