Erdem C.
Erdem C.

Reputation: 9

How to delete multiple spaces in .txt from PHP

this is my txt file

I'm adding data from .txt to database with this code:

$dosya=new SplFileObject('veriler.txt');
while(!$dosya->eof())
{
    $satir=$dosya ->fgets();
    list($name,$section,$initialname)=explode(' ',$satir);
     
   $sth= $baglan->prepare('INSERT INTO tablo1 values (NULL,?,?,?,NULL)');
    $sth->bindValue(1,$name,PDO::PARAM_STR);
    $sth->bindValue(2,$section,PDO::PARAM_INT);
    $sth->bindValue(3,$initialname,PDO::PARAM_STR);
    $sth->execute();
     
}

In the .txt if there is a 1 space between the words, my program is working. But as you can see, there are more than one space in my txt file. How can i delete/remove multiple spaces in .txt file? If you can show me in my codes, i will be glad. Thank you.

Upvotes: 1

Views: 89

Answers (3)

threeside
threeside

Reputation: 358

@Crisoforo Gaspar solution in your code :

    $dosya=new SplFileObject('veriler.txt');
while(!$dosya->eof())
{
    $satir=$dosya ->fgets();
    $satirWithoutManySpaces = preg_replace("/\s{2,}/", ' ', $satir);
    list($name,$section,$initialname)=explode(' ',$satirWithoutManySpaces);

   $sth= $baglan->prepare('INSERT INTO tablo1 values (NULL,?,?,?,NULL)');
    $sth->bindValue(1,$name,PDO::PARAM_STR);
    $sth->bindValue(2,$section,PDO::PARAM_INT);
    $sth->bindValue(3,$initialname,PDO::PARAM_STR);
    $sth->execute();

}

Hope this help

Upvotes: 0

Crisoforo Gaspar
Crisoforo Gaspar

Reputation: 3830

You can use a regular expression as well to archive the same result.

<?php
// Your code here!
$string = "This  has    too  many spaces";
$result = preg_replace("/\s{2,}/", ' ', $string);
echo($result);
?>

Where /\s{2,}/ means after 2 spaces replace it with a single space also consider that \s also means any of the following characters:

  • \r
  • \n
  • \t
  • \f
  • \v
  • (empty space)

Link: https://paiza.io/projects/M6eSG1zHIUdG5IZEXFZQog

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

You can read more about this over here: https://www.regular-expressions.info/shorthand.html

Upvotes: 1

symlink
symlink

Reputation: 12209

explode() the string, remove array elements with whitespace, and implode():

<?php
    $string = "This  has    too  many spaces";
    $array = explode(" ", $string);
    $array = array_filter($array); 
    $result = implode(" ", $array);
    echo($result);
?>

https://paiza.io/projects/Bi-2H7HiPIklLwXGfYAqCg

Upvotes: 0

Related Questions