PHP-如何通过将密钥与RegexP匹配来搜索关联数组



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

样本输入可能是:

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

目前我有以下方法:

// Setup an assoc_array what regexp match should be mapped to which itemId
private $itemIdMap = [ '/paperstowels/' => '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((:定界符不得是字母数字或backslash

我在做什么错,如何解决?

preg_grep手动参数顺序中为:

string $pattern , array $input

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

所以,您的电话是

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

那么,您是否真的尝试在数字3746473294中找到字符串We need to buy paper towels

因此,第一个修复可以是 -swap'em,并将第二个论点归为 array

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

,但这里出现第二个错误-$itemIdMap是数组。您不能将数组用作REGEXP。只能使用标量值(更严格的字符串(。这会导致您:

$match = preg_grep($map['/paperstowels/'], $key);

哪个绝对不是您想要的,对

解决方案

$input = 'We need to buy paper towels.';
$itemIdMap = [
    '/paperstowels/' => '3746473294',
    '/othersstuff/' => '234432',
    '/tosbuy/' => '111222',
];
foreach ($itemIdMap as $k => $v) {
    if (preg_match($k, $input)) {
        echo $v . PHP_EOL;
    }
}

您的错误假设是,您认为可以在带有preg_grep的单个字符串中从Regexps数组中找到任何项目,但这不是正确的。相反,preg_grep搜索数组的元素,该元素适合一个单一的正格版。因此,您只是使用了错误的功能。

最新更新