我有一个文本文件:
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
我以前问过一个问题,但答案对我来说太“专业”了,我真的需要一个新手证明的解决方案/答案。我一整天都在尝试弄清楚它,但我就是无法让它工作。
编辑: 问题已解决!非常感谢您的时间和帮助,我希望这可能对其他人有用!
if
条件语句的末尾使用break;
可能会很有用。 - ner0