Home >php教程 >php手册 >php读取文本去除空格

php读取文本去除空格

WBOY
WBOYOriginal
2016-06-13 08:53:141086browse

php读取文本去除空格

  在使用php对mysql进行处理时,有时候要对文件内容进行读取并输出,处理时发现php对读取的文件内容输出字符串后面会有一个空格,从而影响某些操作

 

例如:文件 2.txt 内容如下

 

 

123
234
abc

 

 

php脚本

file.php

 

 

<?php
$con = mysql_connect("localhost","root","111111");
if (!$con)
{
die(&#39;Could not connect:&#39; .mysql_error());
}
mysql_select_db("zzadmin",$con);
$file=file(&#39;2.txt&#39;);
$arrlength=count($file);
for ($x=0;$x<$arrlength;$x++) {
$b=$file[$x];
$sql = "INSERT INTO csdn_db (username,passwd,email) SELECT username,passwd,email FROM csdn where passwd like &#39;$b%&#39;";
var_dump($sql);
echo "<p>";
?>

 

 

 

如图1

 

 

 

查阅资料发现可以通过PHP trim()函数解决此问题

 

方法如下:

 

trim() 去除一个字符串两端空格, 

rtrim() 是去除一个字符串右部空格, 

ltrim() 是去除一个字符串左部空格。 

 

-------------------------------------

 

 

更改脚本:

 

<?php
$con = mysql_connect("localhost","root","111111");
if (!$con)
{
die(&#39;Could not connect:&#39; .mysql_error());
}
mysql_select_db("zzadmin",$con);
$file=file(&#39;2.txt&#39;);
$arrlength=count($file);
for ($x=0;$x<$arrlength;$x++) {
$c=$file[$x];
$b=rtrim($c);   
//添加函数
$sql = "INSERT INTO csdn_db (username,passwd,email) SELECT username,passwd,email FROM csdn where passwd like &#39;$b%&#39;";
var_dump($sql);
echo "<p>";
>

 

 

如图2  

 

 

OK  完美解决

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn