如何从PHP中删除.txt中的多个空格

如何从PHP中删除.txt中的多个空格,php,Php,我正在使用以下代码将.txt中的数据添加到数据库: $dosya=newsplfileobject('veriler.txt'); 而(!$dosya->eof()) { $satir=$dosya->fgets(); 列表($name,$section,$initialname)=分解(“”,$satir);       $sth=$baglan->prepare('INSERT INTO tablo1 values(NULL、、、、、、NULL)'); $sth->bindValue(1,

我正在使用以下代码将.txt中的数据添加到数据库:

$dosya=newsplfileobject('veriler.txt');
而(!$dosya->eof())
{
$satir=$dosya->fgets();
列表($name,$section,$initialname)=分解(“”,$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();
     
}
分解()
字符串,删除带有空格的数组元素,然后
内爆()



您也可以使用正则表达式来归档相同的结果

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

<> > <代码>/\s{2,}/< /> >在2个空间用单个空间替换它之后,也考虑<代码> 也意味着以下任何字符:

  • \r
  • \n
  • \t
  • \f
  • \五
  • (空白)
链接:

\s代表“空白字符”。同样,这实际上包括哪些字符,取决于正则表达式的风格。在本教程讨论的所有版本中,它都包括[\t\r\n\f]。即:\s匹配空格、制表符、回车符、换行符或换行符


您可以在此处阅读更多信息:

@Crisoforo Gaspar解决方案代码:

    $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();

}

希望这有助于

所以在OPs的情况下这将是
列表($name,$section,$initialname)=数组_过滤器(explode(''.$satir))?他们最好把它分成几行。谢谢你的回答,在字符串中它起作用了,但我想替换我的.txt文件,所有单词都应该是1个空格。我是php的业余爱好者,很抱歉我的问题很简单,我可能想使用
\h
来代替,只匹配水平空格。不过,这取决于他想对新词做什么。根据regular-expressions.info,
\s
与整个
\v
不匹配,但只匹配
\r
\n
\f
(表单提要字符)。谢谢,我认为这是一个很好的建议。它不起作用,我的.txt文件是:,当我编写代码时,它是这样添加的数据库:,你说得对,我犯了个错误。我认为您应该在$satir var上使用@Crisoforo解决方案,然后可以使用explode函数。这应该像预期的那样起作用。我编辑我的答案
    $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();

}