【发布时间】:2018-05-22 14:07:20
【问题描述】:
我有一个变量$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";
}
【问题讨论】: