【问题标题】:Search text file for value and return everything after it在文本文件中搜索值并返回其后的所有内容
【发布时间】: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";
}

【问题讨论】:

    标签: php regex


    【解决方案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
    

    【讨论】:

    • 非常感谢。 $contents 会是people.txt吗?
    • @michaelmcgurk,这是你的真实$contents = file_get_contents($file);
    【解决方案2】:

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

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

    \b$pattern[\s\S]*
    

    【讨论】:

    • 非常感谢@user3783243 - 现在就试一试。
    • 哦,我可能看错了,你想要比赛结束后的一切,还是只想要比赛直到|?从标题我把它读成一切。
    【解决方案3】:
    $pattern = "/^.*$pattern@([^|]+\)|/m";
    

    [^|]+ 表示任何字符,至少一次 (+),但不是 |

    \| 转义 | 因为它在这种情况下有意义

    () 是一个捕获组,它允许您稍后在$matches 中引用捕获的值。由于您使用preg_match_all,因此第一个捕获组(也是唯一一个)的所有匹配项都将在$matches[1] 提供。

    【讨论】:

    • 你说要匹配到|
    • 不是我的问题,但我想取决于。问题因return everything after itbefore the pipe 而异。
    • @michaelmcgurk 所以现在你删除了你的评论并基本上接受了一个非常相似的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    相关资源
    最近更新 更多