簡體   English   中英

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

[英]PHP search for string in text file & return result after specific character

我想在文本文件中搜索字符串。 查找結果並在:字符后返回。

輸入的是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

也許不是最好的解決方案,但是您可以在陣列上使用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.':');

您可以使用正則表達式匹配來定位以給定輸入開頭的行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM