PHP从文本文件中获取价值 [英] Php get value from text file

查看:77
本文介绍了PHP从文本文件中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文本文件:

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

我想完成的是,如果我寻找" foo,它返回bar(如果我寻找bing,它应该返回bong).尝试执行此操作的一种方法是,首先搜索文件,返回结果行,将其放入字符串中,然后删除:"之前的所有内容并显示该字符串.

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.

来源: 许多stackoverflow链接以及可比较的搜索:
https://www.google.com/search?client = opera& q = php +删除+一切+之后
https://www.google.com/search?client = opera& q = php + search + text + file + return + line

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.

解决了!非常感谢您的时间&帮助,希望对其他人有帮助!

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

推荐答案

这应该可以满足您的需求,我已经在服务器上对其进行了测试,它似乎可以满足您的需求.

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;

?>

这篇关于PHP从文本文件中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆