gpt4 book ai didi

php从文本文件中获取值

转载 作者:行者123 更新时间:2023-12-02 07:35:06 25 4
gpt4 key购买 nike

我有这个文本文件:

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;

?>

关于php从文本文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com