Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 搜索文本文件中的值并返回其后面的所有内容_Php_Regex - Fatal编程技术网

Php 搜索文本文件中的值并返回其后面的所有内容

Php 搜索文本文件中的值并返回其后面的所有内容,php,regex,Php,Regex,我有一个变量$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'; // th

我有一个变量
$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";
}

您正在使用
\$
查找文本
\$
,请删除反斜杠,您应该很好

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

\b$pattern[\s\S]*
[^ |]+
表示任何字符,至少一次(
+
),但不是

\\\\\
转义
\
,因为它在这种上下文中很有意义


()
是一个捕获组,它允许您稍后在
$matches
中引用捕获的值。由于您使用的是
preg\u match\u all
,因此第一个捕获组(以及唯一一个)的所有匹配项将在
$matches[1]

处可用。请使用以下方法:

$search_for = 'my.name';

$pattern = sprintf('/\b%s@([^|\s]+)\|/m', preg_quote($search_for));

if (preg_match_all($pattern, $contents, $matches)) {
   echo "Found matches:\n";
   echo implode("\n", $matches[1]);
} else {
   echo "No matches found";
}
当前输入片段的输出:

Found matches:
mysite.com

非常感谢@user3783243-我现在就试试。哦,我可能误读了,你是想在比赛结束后得到一切,还是只想在比赛结束前得到一切?从标题上看,我把它理解为一切。非常感谢。$contents是否为
people.txt
?@michaelmcgurk,这是您实际的
$contents=file\u get\u contents($file)
你说你想匹配到
|
。这不是我的问题,但我想要看情况而定。问题不尽相同
返回它之后的所有内容
或管道之前的所有内容
@michaelmcgurk,所以现在您删除了您的评论,基本上接受了一个非常类似的答案。
Found matches:
mysite.com