Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 262
  • Last Modified:

Trimming the file using PHP

How to trim the file using PHP.

The Input file is,
`````````````
         ;           Zone file for sasikumar.com

ns              A       12.168.1.24

email           A       12.168.1.24
                MX      10 email

www               A   61.12.281.126
               MX   10 mail        


The Output should be,
``````````````````
; Zone file for sasikumar.com

ns A 12.168.1.24

email A 12.168.1.24
MX 10 email

www A 61.12.281.126
MX 10 mail        

There should be only one space between the words.

Regards,
Sasikumar Natarajan
Chennai
0
isas_n
Asked:
isas_n
1 Solution
 
BatalfCommented:
try

<?php

$fh = fopen("textFile.txt","r");
$data = fread($fh,filesize("textFile.txt"));
fclose($fh);

$data = preg_replace("/(\s)\s+/si","\\1",$data);

echo $data; // With only one space.

?>
0
 
RoonaanCommented:
Even shorten.

$file = file_get_contents("myfile.zone.txt");
$file = preg_replace("/([\s])[\s]+/","\\1",$file);

No use of having the /i modifier, as you are matching whitespaces...

-r-
0
 
BatalfCommented:
I know :-) The "i"(case insensitive) flag isn't needed. I put it there by mistake since I so often use it in regexp.

/(\s)\s+/s

should be enough.

0
 
lokipCommented:
The replacement string should be " " not "\\1" as the zone files he is modifying may have tabs and he wanted spaces, and tabs do match in \s, thus Roonaan's example becomes:

$file = file_get_contents( "myfile.zone.txt" );
$file = preg_replace( "/([\s])[\s]+/", " ", $file );
0
 
hujiCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned..
I will leave the following recommendation for this question in the Cleanup topic area:
Accept: Batalf {http:#13680589}

Any objections should be posted here in the next 4 days. After that time, the question will be closed.

Huji
EE Cleanup Volunteer
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now