PHP在文本文件中搜索字符串,并在特定字符后返回结果

时间:2019-06-14 17:41:32

标签: php string

我要在文本文件中搜索字符串。查找结果并在字符后返回。

输入为Alex 文本文件包含此项

alex:+123
david:+1345
john:+1456

输出为+123

$input = "alex";
file_get_contents("TextFilePath");

//in this step i don't know what should i do

2 个答案:

答案 0 :(得分:1)

也许不是最好的解决方案,但是您可以使用file并在数组上循环。 explode每行查看是否有针头。

function findInAFile($filename, $needle) {
    // read file split on newline
    $lines = file($filename);
    // check each line and return first occurence
    foreach ($lines as $line) {
        $arr = explode($needle, $line, 2);
        if (isset($arr[1])) {
            return $arr[1];
        }
    }
}

echo findInAFile('file.txt', $input.':');

答案 1 :(得分:0)

您可以使用正则表达式匹配来定位以给定输入开头的行:

$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
    // Found input
    var_dump($match[1]);
}