加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Php从文本文件中获取值

发布时间:2020-12-13 13:44:34 所属栏目:PHP教程 来源:网络整理
导读:我有这个文本文件: foo: barel: machobing: bongcake color: blue berrymayo: ello 我想要完成的是,如果我“寻找”foo,它会返回bar(如果我寻找bing,它应该返回bong).尝试完成此操作的方法是首先搜索文件,返回带有结果的行,将其放在字符串中并删除“:”之前
我有这个文本文件:
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello

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

// 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;

但它不起作用.这里只是我尝试过的众多事情之一.

资料来源:
许多stackoverflow链接和可比搜索:
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

我之前问过一个问题,但对我来说答案是“专业”,我真的需要一个禁止使用的解决方案/答案.我一直试图弄明白,但我无法让它发挥作用.

编辑:
它解决了!非常感谢你的时间和帮助,我希望这可能对其他人有用!

这应该适用于您正在寻找的东西,我在我的服务器上测试它,它似乎适合您正在寻找的.
$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;

?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读