3

我有这个文本文件:

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 +搜索+文本+文件+返回+行

我以前问过一个问题,但答案对我来说是“专业的”,我真的需要一个菜鸟证明的解决方案/答案。我整天都在想办法解决这个问题,但我就是无法让它发挥作用。

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

4

5 回答 5

6

这应该适用于您正在寻找的东西,我在我的服务器上对其进行了测试,它似乎适合您正在寻找的东西。

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

?>
于 2013-06-30T18:25:18.027 回答
2

我会这样做:

foreach($lines as $line)
{
  // explode the line into an array
  $values = explode(':',$line);
  // trim the whitspace from the value
  if(trim($values[1]) == $search)
  {
      echo "found value for ".$search.": ".$values[1];
      // exit the foreach if we found the needle
      break;
  }
} 
于 2013-06-30T18:26:07.537 回答
1
 $search = 'bing';
 // Read from file
 $lines = file('text.txt');

 $linea='';
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) {
  $liner=explode(': ',$line);
  $linea.= $liner[1];
  }

  }

  echo 'Search returned: '. $linea;

说明: - $linea var 在循环之前创建,它将包含搜索结果。如果在线上找到值 - 分解字符串,并制作数组,从数组中获取第二个 var,将其放入搜索结果容器变量中。

于 2013-06-30T18:26:17.063 回答
1

由于您的数据几乎是YAML [参见 lint ],因此您可以使用解析器来获取关联的 PHP 数组。

但是,如果也可以使用您的解决方案:

 // 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 array_pop(explode(":", $line));

    }

  }
于 2013-06-30T18:27:41.667 回答
0

使用fgetcsv

$bits = array();

if (($handle = fopen('t.txt','r')) !== FALSE) {
  while (($data = fgetcsv($handle, 0, ":")) !== FALSE) {
    $bits[$data[0]] = $data[1];
  }
}

# Now, you search

echo $bits['foo'];

$bits每个拆分部分都有一个密钥,这使您的最终目标变得非常简单。这是它的样子:

Array
(
    [foo] =>  bar
    [el] =>  macho
    [bing] =>  bong
    [cake color] =>  blue berry
    [mayo] =>  ello
)
于 2013-06-30T18:31:42.103 回答