【问题标题】:How to extract specific text from a text file in php?如何从php中的文本文件中提取特定文本?
【发布时间】:2018-12-14 03:42:08
【问题描述】:

我在从文本文件中提取特定文本时遇到困难。我尝试了许多不同的方法,例如使用 fopen 或 file 打开文件,但这不允许我使用任何字符串函数。所以我决定使用 file_get_contents 并使用字符串方法提取我想要的文本,如下所示:

    <?php  

        $data = [];  
        $file =   
        file_get_contents("data.txt", 0, NULL, 148);  
             list($id, $data_names) = preg_split('[:]', $file);  
             array_push($names, $data_names);  
             echo $emails[0];  

    ?>  

我使用 preg_split 将我想要的文本拆分为特定字符 (:),并将数据放入数组中。这适用于第一行,但我不知道如何为其余的行执行此操作,我尝试了一个 while 循环,但最终进入了无限循环。

data.txt 格式如下:

1:hannah.Smith
2:Bob.jones
3:harry.white
....

任何有关如何执行此操作或更好方法的建议将不胜感激。

【问题讨论】:

标签: php arrays loops


【解决方案1】:

有一个功能。这不是 CSV,而是更改分隔符。仅获取名称:

$handle = fopen("data.txt", "r"));
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
    $names[] = $line[1];
}

按 id 索引名称:

while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
    $names[$line[0]] = $line[1];
}

要获取多维数组中的 id 和名称,请使用:

while(($names[] = fgetcsv($handle, 0, ":")) !== FALSE) {}

【讨论】:

    【解决方案2】:

    好吧,您没有将 file_get_contents 的返回值分配给变量。所以文件的内容没有被使用。

    您可以使用file 函数。它将文件的内容读取到数组中。数组的每个元素都是文件中的一行。然后,您可以遍历数组并解析每一行。例如:

    $names = array();
    $file  = file_get_contents("data.txt");
    
    for ($count = 0; $count < count($file); $count++) {
        list($id, $name) = $file[$count];
        $names[]         = $name;
    }
    
    /** print the contents of the names array */
    print_R($names);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2011-06-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多