首页 > 解决方案 > 从txt文件中获取特定数据

问题描述

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

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

里面的结构是这样的:

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

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

标签: php

解决方案


您可以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>';

推荐阅读