php - 在文本文件中搜索值并返回其后的所有内容
问题描述
我有一个变量$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]*
推荐阅读
- ajax - 如何使用ajax更改laravel中的错误302
- while-loop - SyntaxError:解析时出现意外的 EOF - tn.close()
- java - Spring-Boot-Admin 服务器无法从 Eureka 注册中心注册客户端
- php - 个人资料图片上传和图片裁剪 PHP
- python - 在Python中逐年计算每个月的平均值
- macos - 修复 Mac 上的文件权限
- r - 为什么将日期时间放入R中的向量时会转换时区?
- swift - 如何暂停 touchesBegan 并且只使用 touchesMoved 反之亦然?
- javascript - 当我点击视频时,它不会弹出 [Jquery]
- python - Matplotlib饼图楔形透明度?