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

这是我的 txt 文件

我使用以下代码将数据从 .txt 添加到数据库:


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

     

}

在 .txt 中,如果单词之间有 1 个空格,则我的程序正在运行。但是大家可以看到,我的txt文件里面不止一个空格。如何删除/移除 .txt 文件中的多个空格?如果你能用我的代码告诉我,我会很高兴。谢谢你。


明月笑刀无情
浏览 90回答 3
3回答

ABOUTYOU

您也可以使用正则表达式来存档相同的结果。<?php// Your code here!$string = "This&nbsp; has&nbsp; &nbsp; too&nbsp; many spaces";$result = preg_replace("/\s{2,}/", ' ', $string);echo($result);?>Where/\s{2,}/表示在 2 个空格后将其替换为一个空格也认为这\s也表示以下任何字符:\r\n\t\F\在(空的空间)链接:https ://paiza.io/projects/M6eSG1zHIUdG5IZEXFZQog\s 代表“空白字符”。同样,这实际上包括哪些字符取决于正则表达式的风格。在本教程中讨论的所有风格中,它包括 [ \t\r\n\f]。即:\s 匹配空格、制表符、回车符、换行符或换页符。您可以在这里阅读更多相关信息:https ://www.regular-expressions.info/shorthand.html

郎朗坤

explode()字符串,删除带有空格的数组元素,以及implode():<?php&nbsp; &nbsp; $string = "This&nbsp; has&nbsp; &nbsp; too&nbsp; many spaces";&nbsp; &nbsp; $array = explode(" ", $string);&nbsp; &nbsp; $array = array_filter($array);&nbsp;&nbsp; &nbsp; $result = implode(" ", $array);&nbsp; &nbsp; echo($result);?>https://paiza.io/projects/Bi-2H7HiPIklLwXGfYAqCg

慕容森

&nbsp; &nbsp;$dosya=new SplFileObject('veriler.txt');while(!$dosya->eof()){&nbsp; &nbsp; $satir=$dosya ->fgets();&nbsp; &nbsp; $satirWithoutManySpaces = preg_replace("/\s{2,}/", ' ', $satir);&nbsp; &nbsp; list($name,$section,$initialname)=explode(' ',$satirWithoutManySpaces);&nbsp; &nbsp;$sth= $baglan->prepare('INSERT INTO tablo1 values (NULL,?,?,?,NULL)');&nbsp; &nbsp; $sth->bindValue(1,$name,PDO::PARAM_STR);&nbsp; &nbsp; $sth->bindValue(2,$section,PDO::PARAM_INT);&nbsp; &nbsp; $sth->bindValue(3,$initialname,PDO::PARAM_STR);&nbsp; &nbsp; $sth->execute();}希望这有帮助
打开App,查看更多内容
随时随地看视频慕课网APP