André Oliveira
André Oliveira

Reputation: 1123

Removing spaces from a text file using PHP

I need to add itens from a text file, into a MySQL database, to do that i'm trying to use PHP to read the file and insert everything into the database, the problem is that the text file, has 2 itens per line, divided by spaces, something like this:

teste.txt
    ITEM1      ITEM2
    ITEM323    ITEM4
    ITEM54     ITEM6
    ITEM34234  ITEM8

I'm trying to remove the spaces using explode, but because the number of spaces, is random, i cannot do that. This is my Code:

$handle = @fopen("teste.txt", "r"); //read line one by one


while (!feof($handle)) // Loop til end of file.
{
    $buffer = fgets($handle, 4096); // Read a line.
    list($a,$b)=explode(" ",$buffer);//Separate string by Spaces
    //values.=($a,$b);// save values and use insert query at last or

   echo $a;
   echo "<br>";
   echo $b . "<br>"; // NEVER echoes anything

 }

What should i do?

Upvotes: 0

Views: 2318

Answers (2)

Reflection
Reflection

Reputation: 2106

You can use preg_replace() to perform a regular expression:

$buffer = preg_replace("/\ +/", " ", fgets($handle, 4096));

Upvotes: 0

Anonymous
Anonymous

Reputation: 12017

You can insert a method to change multiple spaces to one:

$buffer = preg_replace('/\s+/',' ',$buffer);

Right before exploding it:

$buffer = fgets($handle, 4096); // Read a line.
$buffer = preg_replace('/\s+/',' ',$buffer);
list($a,$b)=explode(" ",$buffer);//Separate string by Spaces

Upvotes: 1

Related Questions