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

时间:2012-04-20 17:05:10

标签: php arrays string foreach strpos

我的文本注册表数据如下:

/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 = explode“\ n”并在下面创建数组列表:

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包含“time.dll”,所以代码产生如下结果:

var_dump($seperate);

[1]=> string(89) "/Classes/CLSID/InprocServer32/,C:\x5CWINDOWS\x5Csystem32\x5Cmstime.dll," 

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

输出应为空。

让我说我将“\ x5C”替换为空格,有什么功能可以完成这项工作吗?提前谢谢你。

1 个答案:

答案 0 :(得分:2)

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,

如果您不熟悉Regular Expressions,那么它们非常棒且功能强大。您可以根据需要自定义我的。