我有一个包含这样的文件:
test:fOwimWPu0eSaNR8 test2:vogAqsfXpKzCfGr
我希望能够在文件中搜索说测试,然后将字符串设置为:变量,以便可以显示,使用等.
$file = 'file.txt'; $string = 'test'; $searchFile = file_get_contents($file); if (preg_match('/\\b'.$string.'\\b/',$searchFile)) { echo 'true'; // Find String } else { echo 'false'; }
我该怎么做呢?
这应该适合你:
只需将文件放入带有file()的数组中,然后简单地将preg_grep()放入所有行,这些行在冒号前面都有搜索字符串.
<?PHP $file = "file.txt"; $search = "test"; $lines = file($file,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $matches = preg_grep("/^" . preg_quote($search,"/") . ":(.*?)$/",$lines); $matches = array_map(function($v){ return explode(":",$v)[1]; },$matches); print_r($matches); ?>
输出:
Array ( [0] => fOwimWPu0eSaNR8 )