首页 > 解决方案 > 在文本文件中搜索值并返回其后的所有内容

问题描述

我有一个变量$name = 'my.name';

我有一个名为的文本文件people.txt,其中包含以下内容:

my.name@mysite.com|
my.friend@othersite.com|
my.enemy@anothersite.com|

我希望能够使用该变量来基本上搜索文本文件的内容并返回值mysite.com。所以基本上,my.name管道之前的任何内容。


到目前为止,这是我的脚本:

$file = "people.txt";
$searchfor = 'my.name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

标签: phpregex

解决方案


您正在寻找$带有\$删除反斜杠的文字,您应该很好。

具有相同结果的替代模式可能是:

\b$pattern[\s\S]*

推荐阅读