【问题标题】:Get specific data from txt file从txt文件中获取特定数据
【发布时间】:2019-07-25 09:19:57
【问题描述】:

我有 txt 文件,我需要在循环中回显特定数据。

假设我的 txt 文件名是这样的:myfile.txt

里面的结构是这样的:

etc="Orange" src="stack1"
etc="Blue" src="stack2"
etc="Green" src="stack3"
etc="Red" src="stack4"

如何在 PHP 中回显这些值:橙色、蓝色、绿色、红色?

【问题讨论】:

  • 有了split和arrays就可以搞定。
  • 你好。你能用代码作为答案告诉我吗?
  • 一个关于javascript的例子可以是这个答案,但我可以做到。 stackoverflow.com/questions/57178212/…
  • 试试 print_r(explode('"',file_get_contents('your_text_file.txt'))) 看看你会得到什么。

标签: php


【解决方案1】:

您可以为此使用preg_match_all

<?php
    # get your text
    $txt = file_get_contents('your_text_file.txt');

    # match against etc="" (gets val inside the quotes)
    preg_match_all('/etc="([^"]+)"/', $txt, $matches);

    # actual values = $matches[1]
    $values = $matches[1];

    echo '<pre>'. print_r($values, 1) .'</pre>';

【讨论】:

  • SO 的重点是帮助人们修复他们的代码。不为他们编写代码。
  • @MilanG 对,我们没有被雇用嘿嘿。
【解决方案2】:
$content = file_get_content("/path/to/myfile.txt", "r");
if (false === $content) {
  // handle error if file can't be open or find
}

preg_match_all('/etc="(.*?)"/', $content, $matches);

echo implode($matches[1], ',');

使用file_get_content,您可以检索文件中的内容。
之后,您需要检查 file_get_content 是否返回了错误代码(在这种情况下为 false)。
preg_match_all 将使用 RegExp 仅过滤掉您需要的内容。特别是:

/ #is a delimiter needed 
etc=" #will match literally the letters etc="  
(.*?) #is a capturing group needed to collect all the values inside the "" part of etc value. So, capturing group is done with (). .* will match every character and ? make the quantifier "non greedy".
/ #is the ending delimiter

所有匹配都收集在 $matches 数组中(不必事先定义 $matches

最后,您需要将收集到的值转换为字符串,您可以使用implode 函数完成此操作。

【讨论】:

    【解决方案3】:

    我在代码//comments 上解释了所有内容。

    
    <?php
    
    $fichero = file_get_contents('./myfile.txt', false);
    
    if($fichero === false){ //if file_get_contents() return false, the file isn't found, if its found, return data.
        echo "Can't find file.\n";
    }else{ //If file is find, this condition is executed.
        $output = array(); //this variable is who will get the output of regular expression pattern from next line function.
        preg_match_all('/([A-Z])\w+/',$fichero, $output);
        for($i = 0; $i < count($output[0]); $i++){ //Iterate throught the first array inside of array of $output, count(array) is for get length of array.
    
            echo $output[0][$i]; //Print values from array $output[0][$i]
            if($i + 1 != count($output[0])){ //if not equal to length of array, add , at end of printed value of output[0][$i]
                echo ', ';
            }else{ //if equal to length of array, add . at end of printed value of $output[0][$i]
                echo '.';
            }
    
        }
    }
    
    ?>
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多