【问题标题】:explode is not working to split string爆炸无法拆分字符串
【发布时间】:2010-05-17 13:52:22
【问题描述】:

我们无法拆分代码后面的字符串。请帮助我们。

 <?php
$i=0;
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "no\t";
fwrite($fh, $stringData);
$stringData = "username \t";
fwrite($fh, $stringData);
$stringData ="password \t";
fwrite ($fh,$stringData);

$newline ="\r\n";
fwrite ($fh,$newline);
$stringData1 = "1\t";
fwrite($fh, $stringData1);
$stringData1 = "srinivas \t";
fwrite($fh, $stringData1);
$stringData1 ="malayappa \t";
fwrite ($fh,$stringData1);


fclose($fh);



?>
$fh = fopen("testFile.txt", "r");
$
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
}

fclose($fh);
$Beatles = array('pmm','malayappa','sreenivas','PHP');

for($i=0;$i<count($Beatles);$i++)
{
if($i==2)
{

echo $Beatles[$i-1];
echo $Beatles[$i-2];

}
}
$pass_ar=array();
$fh = fopen("testFile.txt", "r");
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
$t1=explode(" ",$line);

print_r($t1);
array_push($pass_ar,t1);
}

fclose($fh);

【问题讨论】:

  • 修正了你的格式(至少一点点)。请创建一个带有示例字符串的测试用例和您的分解,这可能有助于我们为您提供帮助。
  • 请具体说明什么不起作用以及您尝试拆分的数据是什么样的。
  • print_r($t1); 的输出是什么?
  • 请以正确的方式格式化代码,以便任何人都可以阅读。另请澄清您的问题,提供例如你想得到的输出/结果和你当前得到的输出/结果。

标签: php file text


【解决方案1】:

如果我正确阅读了代码,您正在编写由 \t 分隔的字符串,但尝试用空格爆炸,请使用:

explode("\t", $string);

【讨论】:

    【解决方案2】:

    你可以使用fgetcsv,因为你只是在做一个标准的制表符分隔的输入文件。鉴于您的示例文件:

    no [tab] username [tab] password
    1  [tab] srinivas [tab] malayappa
    

    然后

    $lines = array();
    $fh = fopen('testfile.txt', 'rb') or die ("can't open testfile.txt");
    while($lines[] = fgetcsv($fh, 0, "\t") { // no line length limit, tab delimiter)
       ...
    }
    

    会给你

    $lines = Array(
        0 => Array(
             0 => 'no ',
             1 => 'username ',
             2 => 'password '
        ),
        1 => Array(
             0 => 1,
             1 => 'srinivas ',
             2 => 'malayappa'
        )
    );
    

    【讨论】:

      【解决方案3】:

      你在空白处爆炸。除非你爆炸的字符串中有空格然后没有,否则它将不起作用。

      尝试使用代码标记使您的代码更具可读性,以便从人们那里获得更高质量的响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-09
        • 2020-12-10
        相关资源
        最近更新 更多