[英]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.