【问题标题】:PHP explode function with file_get_contents?PHP 用 file_get_contents 爆炸函数?
【发布时间】:2011-05-02 09:54:35
【问题描述】:
   <?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

上面的代码打印一个数组作为输出。

如果我使用

<?php
$homepage = file_get_contents('http://www.example.com/data.txt');
print_r (explode(" ",$homepage));
    ?>

但是它不会在文本文件中以数组的形式显示单个数字。

最终我想从文本文件中读取数字并打印它们的频率。 data.txt 有 100,000 个数字。每行一个数字。

【问题讨论】:

  • 你得到任何结果了吗?您确定这些数字没有被其他空白字符(如制表符)分隔吗?
  • 当我使用“\n”时,我得到了结果。

标签: php explode


【解决方案1】:

换行不是空格。您必须在适当的换行符组合处爆炸。例如。对于 Linux:

explode("\n",$homepage)

或者,您可以使用preg_split 和匹配每个空白字符的字符组\s

preg_split('/\s+/', $homepage);

另一种选择(可能更快)可能是使用fgetcsv

【讨论】:

    【解决方案2】:

    如果你想要一个文件的内容作为一个行数组,已经有一个内置函数

    var_dump(file('http://www.example.com/data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    

    Manual: file()

    【讨论】:

      【解决方案3】:

      尝试在“\n”处爆炸

      print_r (explode("\n",$homepage));
      

      也可以看看:

      http://php.net/manual/de/function.file.php

      【讨论】:

        【解决方案4】:

        您也可以使用正则表达式来解决它:

        $homepage = file_get_contents("http://www.example.com/data.txt");
        preg_match_all("/^[0-9]+$/", $homepage, $matches);
        

        这将为您提供包含数字数组的变量 $matches。这将确保它只检索包含数字的行,以防文件格式不正确。

        【讨论】:

          【解决方案5】:

          您没有使用正确的字符来分解字符串。您要么需要在新行分隔符 (\n) 上爆炸,要么使用正则表达式(会更慢但更健壮)。在这种情况下,请使用preg_split

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-07-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多