代码之家  ›  专栏  ›  技术社区  ›  michaelmcgurk

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

  •  1
  • michaelmcgurk  · 技术社区  · 8 年前

    我有一个变量 $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";
    }
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   RomanPerekhrest    8 年前

    使用以下方法:

    $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
    
        2
  •  1
  •   user3783243    8 年前

    你在寻找一个文字 $ 和 \$ 去掉反斜杠,你应该表现得很好。

    具有相同结果的另一种模式可能是:

    \b$pattern[\s\S]*
    
        3
  •  0
  •   Doka Xec    8 年前
    $pattern = "/^.*$pattern@([^|]+\)|/m";
    

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

    \| 逃脱 | 因为它在这种情况下是有意义的

    () 是一个捕获组,允许您稍后在中引用捕获的值 $matches .既然你用了 preg_match_all ,第一组(以及唯一一组)的所有匹配项将在 $matches[1] .