根据关键字提取数组中的特定 PHP 字符串


Extract specific PHP strings in array based on keywords

我在文本中有注册表数据,如下所示:

/Classes/CLSID/AppID,SZ,{0010890e-8789-413c-adbc-48f5b511b3af},
/Classes/CLSID/InProcServer32,KEY,,2011-10-14 00:00:33
/Classes/CLSID/InProcServer32/,EXPAND_SZ,%SystemRoot%'x5Csystem32'x5CSHELL32.dll,
/Classes/CLSID/InProcServer32/ThreadingModel,SZ,Apartment,
/Classes/CLSID/,KEY,,2011-10-14 00:00:36
/Classes/CLSID/,SZ,,
/Classes/CLSID/InprocServer32,KEY,,2011-10-14 00:00:36
/Classes/CLSID/InprocServer32/,C:'x5CWINDOWS'x5Csystem32'x5Cmstime.dll,

然后我做$registry = 爆炸 "'" 并在下面创建数组列表:

var_dump($registry);
[1]=> string(121) "/Classes/CLSID/AppID,SZ,{0010890e-8789-413c-adbc-48f5b511b3af}," 
[2]=> string(139) "/Classes/CLSID/InProcServer32,KEY,,2011-10-14 00:00:33" 
[3]=> string(89) "/Classes/CLSID/InProcServer32/,EXPAND_SZ,%SystemRoot%'x5Csystem32'x5CSHELL32.dll," 
[4]=> string(103) "/Classes/CLSID/InProcServer32/ThreadingModel,SZ,Apartment," 
[5]=> string(103) "/Classes/CLSID/,KEY,,2011-10-14 00:00:36"
[6]=> string(121) "/Classes/CLSID/,SZ,," 
[7]=> string(139) "/Classes/CLSID/InprocServer32,KEY,,2011-10-14 00:00:36" 
[8]=> string(89) "/Classes/CLSID/InprocServer32/,C:'x5CWINDOWS'x5Csystem32'x5Cmstime.dll," 

我也有数组形式的关键字

var_dump($keywords);
[1]=> string(12) "Math.dll"
[2]=> string(12) "System.dll"
[3]=> string(12) "inetc.dll"
[4]=> string(12) "time.dll"

我想在$registry中显示包含$keywords字符串的行,所以我在下面创建了 1 个函数:

    function separate($line) {
      global $keywords;
      foreach ($keywords as $data_filter) {
          if (strpos($line, $data_filter) !== false) {
        return true;
          }
      }
      return false;
    }
$separate = array_filter($registry, 'separate');

由于在$keywords由"时间.dll"组成,因此代码产生的结果如下:

var_dump($seperate);
[1]=> string(89) "/Classes/CLSID/InprocServer32/,C:'x5CWINDOWS'x5Csystem32'x5Cmstime.dll," 

在我的情况下,结果是不正确的,因为mstime.dll!=时间.dll并且信息不正确。

输出应为空。

假设我将"''x5C"替换为空格,有什么功能可以完成这项工作吗?提前谢谢你。

有preg_match。

要遵循array_filter方式,您必须做事:

function separate($line) {
    global $keywords;
    foreach ($keywords as $data_filter) {
        // '.' means any character in regex, while ''.' means literal period
        $data_filter = str_replace('.', ''.', $data_filter);
        if (preg_match("/''x5C{$data_filter}/", $line)) {
            return true;
        }
    }
    return false;
}

这将返回 false

/Classes/CLSID/InprocServer32/,C:'x5CWINDOWS'x5Csystem32'x5Cmstime.dll,

但对于

/Classes/CLSID/InprocServer32/,C:'x5CWINDOWS'x5Csystem32'x5Ctime.dll,

如果您不熟悉正则表达式,它们很棒且功能强大。您可以根据需要自定义我的以适合您的情况。