我有一个包含以下内容的文件:
苹果100
香蕉200
Cat 300
我想在文件中搜索一个特定的字符串,然后得到下一个单词。我搜索猫,得到300。我查阅了这个解决方案:如何使用Strpos()在Needle之后找到下一个字符串,但这没有帮助,我也没有得到预期的输出。如果您能在不使用regex的情况下提出任何方法,我将非常高兴。
我不确定这是最好的方法,但根据您提供的数据,它会起作用。
- 使用fopen()获取文件的内容
- 使用explode()将值分隔为数组元素
- 遍历数组,并检查每个元素的索引是否为奇数或偶数。复制到新阵列
不完美,但在正确的轨道上。
<?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
)
试试这个,它不使用regex,但如果你搜索的字符串更长,效率会很低:
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
}
$find = 'Apple';
preg_match_all('/' . $find . ''s('d+)/', $content, $matches);
print_r($matches);
您可能会从使用命名regex子模式来捕获您要查找的信息中受益。
例如,你,找到一个数字,单词是它的前一个(1<=值<=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);
在找到匹配项的情况下,结果数组将包含您要查找的索引为"value"的数字。
这种方法可以与相结合
file_get_contents($file);