jdn*_*oon 5 php regex file file-get-contents preg-match
我有一个包含这样的文件:
test:fOwimWPu0eSaNR8
test2:vogAqsfXpKzCfGr
Run Code Online (Sandbox Code Playgroud)
我希望能够在文件中搜索说明test,然后将字符串设置:为变量,以便可以显示,使用等.
这是我到目前为止在文件中找到'test'的代码.
$file = 'file.txt';
$string = 'test';
$searchFile = file_get_contents($file);
if (preg_match('/\\b'.$string.'\\b/', $searchFile)) {
echo 'true';
// Find String
} else {
echo 'false';
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
这应该适合你:
只需将文件放入一个数组中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);
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Array ( [0] => fOwimWPu0eSaNR8 )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1179 次 |
| 最近记录: |