使用PHP在文本文件中查找字符串

时间:2018-06-13 18:46:04

标签: php regex preg-match

我有一个名为peoplelist.txt的文件,其中包含以下文字: 1,mikey.mcgurk,1,boss.man

但是,当我在搜索第二个文件时尝试在我的脚本中使用$name时,它不起作用:(

people.txt的内容只是mikey.mcgurk

因此,如果我使用$searchfor = $name,以下效果很好 BUT ,则会失败。为什么呢?

$handle = fopen("peoplelist.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $parts = explode(',',$line);
        $name = $parts[1] . PHP_EOL;
        $name = strtolower($name);
        $name = str_replace(' ', '.', $name);
        $boss = $parts[3] . PHP_EOL;
    }
    fclose($handle);
}

echo $name; // this echoes out 'mikey.mcgurk', as expected

$file = 'people.txt';
$searchfor = 'mikey.mcgurk';

// 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";
}

注意:这不是2个单独的脚本,它只是一个PHP文件 - 我只是将它拆分为这个问题: - )

1 个答案:

答案 0 :(得分:1)

我认为问题在于正则表达式模式。但是,由于还有其他一些事情可以做得更好,我也加上了。

$list = file_get_contents("peoplelist.txt");
list($something, $name, $somethingelse, $boss) = explode(',',$line);
$name = str_replace(' ', '.', strtolower($name));

echo $name; 

$file = 'people.txt';
$contents = file_get_contents($file);
$pattern = "/" . $name . "/m"; 

if(preg_match_all($pattern, $contents, $matches)){
    echo "Found matches:\n";
    echo implode("\n", $matches[0]);
}
else{
    echo "No matches found";
}

你的正则表达没有意义。你希望它从任何事情开始。
那为什么力量开始?当然还有文字$。