dtwxt88240 2013-06-30 18:11
浏览 56
已采纳

Php从文本文件中获取值

I have this textfile:

foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello

And I what I'm trying to accomplish is that if I "look" for foo, it returns bar (if I look for bing, it should return bong). A way a tried to accomplish this is first search though the file, return the line with the result, put it in a string and remove everything before the ":" and display the string.

// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
    // Check if the line contains the string we're looking for, and print if it does
    if(strpos($line, $search) !== false)
        echo $line;

    $new_str = substr($line, ($pos = strpos($line, ',')) !== false ? $pos + 1 : 0);
} 
echo "<br>";
echo "bing should return bong:";
echo $new_str;

But it doesn't work. Up here is just one of the many things I've tried.

Sources: Many stackoverflow links on and comparable searches:
https://www.google.com/search?client=opera&q=php+remove+everything+after
https://www.google.com/search?client=opera&q=php+search+text+file+return+line

I've asked a question before, but the answers are to "professional" for me, I really need a noob-proof solution/answer. I've been trying to figure it out all day but I just can't get this to work.

Edit: It's solved! Thank you so much for your time & help, I hope this might be useful to someone else to!

  • 写回答

5条回答 默认 最新

  • dqwh0108 2013-06-30 18:25
    关注

    This should work with what you are looking for, I tested it on my server and it seems to fit what you are looking for.

    $lines_array = file("file.txt");
    $search_string = "bing";
    
    foreach($lines_array as $line) {
        if(strpos($line, $search_string) !== false) {
            list(, $new_str) = explode(":", $line);
            // If you don't want the space before the word bong, uncomment the following line.
            //$new_str = trim($new_str);
        }
    }
    
    echo $new_str;
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本