繁体   English   中英

PHP-如何通过将键与正则表达式匹配来搜索关联数组

[英]PHP - How to search an associative array by matching the key against a regexp

我目前正在研究一个小的脚本,以转换来自外部源的数据。 根据内容,我需要将此数据映射到对我的应用程序有意义的内容。

输入示例可以是:

$input = 'We need to buy paper towels.'

目前,我有以下方法:

// Setup an assoc_array what regexp match should be mapped to which itemId
private $itemIdMap = [ '/paper\stowels/' => '3746473294' ];

// Match the $input ($key) against the $map and return the first match
private function getValueByRegexp($key, $map) {
  $match = preg_grep($key, $map);
  if (count($match) > 0) {
    return $match[0];
  } else {
    return '';
  }
}

这会在执行时引发以下错误:

警告:preg_grep():分隔符不得为字母数字或反斜杠

我在做什么错,这怎么解决?

preg_grep ,参数的手动顺序为:

string $pattern , array $input

在您的代码中$match = preg_grep($key, $map); - $key是输入字符串, $map是模式。

所以,你的电话是

$match = preg_grep(
    'We need to buy paper towels.', 
    [ '/paper\stowels/' => '3746473294' ] 
);

那么,您真的尝试找到线吗? We need to buy paper towels数量3746473294吗?

因此,第一个解决方法是 -swap'em并将第二个参数转换为array

$match = preg_grep($map, array($key));

但是这是第二个错误- $itemIdMap是数组。 您不能将数组用作正则表达式。 只能使用标量值(更严格地说是字符串)。 这将导致您:

$match = preg_grep($map['/paper\stowels/'], $key);

绝对不是您想要的,对吗?

解决方案

$input = 'We need to buy paper towels.';
$itemIdMap = [
    '/paper\stowels/' => '3746473294',
    '/other\sstuff/' => '234432',
    '/to\sbuy/' => '111222',
];

foreach ($itemIdMap as $k => $v) {
    if (preg_match($k, $input)) {
        echo $v . PHP_EOL;
    }
}

错误的假设是您认为可以使用preg_grep在单个字符串中preg_grep数组中的任何项,但这是不对的。 相反, preg_grep搜索适合单个正则表达式的数组元素。 因此,您只是使用了错误的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM