0

我有一个文件,内容如下:

苹果100

香蕉 200

猫 300

我想在文件中搜索特定字符串并获取下一个单词。例如:我搜索 cat,我得到 300。我已经查找了这个解决方案:How to Find Next String After the Needle Using Strpos(),但这没有帮助,我没有得到预期的输出。如果您可以在不使用正则表达式的情况下提出任何方法,我会很高兴。

4

4 回答 4

1

我不确定这是最好的方法,但是根据您提供的数据,它会起作用。

  1. 使用fopen()获取文件内容
  2. 使用explode()将值分隔为数组元素
  3. 遍历您的数组并检查每个元素的索引是奇数还是偶数。复制到新数组。

不完美,但在正确的轨道上。

<?php
$filename = 'data.txt'; // Let's assume this is the file you mentioned
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$clean = trim(preg_replace('/\s+/', ' ', $contents));
$flat_elems = explode(' ', $clean);

$ii = count($flat_elems);
for ($i = 0; $i < $ii; $i++) {
    if ($i%2<1) $multi[$flat_elems[$i]] = $flat_elems[$i+1];
}

print_r($multi);

这会输出一个像这样的多维数组:

Array
(
    [Apple] => 100
    [banana] => 200
    [Cat] => 300
)
于 2013-02-20T10:50:58.487 回答
0

You might benefit from using named regex subpatterns to capture the information you're looking for.

For example you, finding a number the word that is its former (1 <= value <= 9999)

/*String to search*/
$str = "cat 300";
/*String to find*/
$find = "cat";
/*Search for value*/
preg_match("/^$find+\s*+(?P<value>[0-9]{1,4})$/", $str, $r);
/*Print results*/
print_r($r);

In cases where a match is found the results array will contain the number you're looking for indexed as 'value'.

This approach can be combined with

file_get_contents($file);    
于 2013-02-20T10:49:52.717 回答
0

试试这个,它不使用正则表达式,但如果您要搜索的字符串较长,它会效率低下:

function get_next_word($string, $preceding_word)
{
  // Turns the string into an array by splitting on spaces
  $words_as_array = explode(' ', $string); 

  // Search the array of words for the word before the word we want to return
  if (($position = array_search($preceding_word, $words_as_array)) !== FALSE)
    return $words_as_array[$position + 1]; // Returns the next word
  else
    return false; // Could not find word
}
于 2013-02-20T10:35:08.400 回答
0
$find = 'Apple';
preg_match_all('/' . $find . '\s(\d+)/', $content, $matches);
print_r($matches);
于 2013-02-20T10:37:11.303 回答