我有这个文本文件:
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
Run Code Online (Sandbox Code Playgroud)
我想要完成的是,如果我“寻找” 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;
Run Code Online (Sandbox Code Playgroud)
但它不起作用。这里只是我尝试过的众多事情之一。
来源:许多 stackoverflow 链接和类似搜索:
https : //www.google.com/search ? client = opera& q = php+ remove+everything+ after
https://www.google.com/search?client=opera&q=php +搜索+文本+文件+返回+行
我以前问过一个问题,但答案对我来说是“专业的”,我真的需要一个 noob-proof 解决方案/答案。我一整天都在试图弄清楚,但我就是无法让它发挥作用。
编辑:已经解决了!非常感谢您的时间和帮助,我希望这对其他人有用!
小智 5
这应该适用于您正在寻找的内容,我在我的服务器上对其进行了测试,它似乎适合您正在寻找的内容。
$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;
?>
Run Code Online (Sandbox Code Playgroud)