简体   繁体   English

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

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

I am currently working on a small script to convert data coming from an external source. 我目前正在研究一个小的脚本,以转换来自外部源的数据。 Depending on the content I need to map this data to something that makes sense to my application. 根据内容,我需要将此数据映射到对我的应用程序有意义的内容。

A sample input could be: 输入示例可以是:

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

Currently I have the following approach: 目前,我有以下方法:

// 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 '';
  }
}

This raises the following error on execution: 这会在执行时引发以下错误:

Warning: preg_grep(): Delimiter must not be alphanumeric or backslash 警告:preg_grep():分隔符不得为字母数字或反斜杠

What am I doing wrong and how could this be solved? 我在做什么错,这怎么解决?

In preg_grep manual order of arguments is: preg_grep ,参数的手动顺序为:

string $pattern , array $input

In your code $match = preg_grep($key, $map); 在您的代码中$match = preg_grep($key, $map); - $key is input string, $map is a pattern. - $key是输入字符串, $map是模式。

So, your call is 所以,你的电话是

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

So, do you really try to find string We need to buy paper towels in a number 3746473294 ? 那么,您真的尝试找到线吗? We need to buy paper towels数量3746473294吗?

So first fix can be - swap'em and cast second argument to array : 因此,第一个解决方法是 -swap'em并将第二个参数转换为array

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

But here comes second error - $itemIdMap is array. 但是这是第二个错误- $itemIdMap是数组。 You can't use array as regexp. 您不能将数组用作正则表达式。 Only scalar values (more strictly - strings) can be used. 只能使用标量值(更严格地说是字符串)。 This leads you to: 这将导致您:

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

Which is definitely not what you want, right? 绝对不是您想要的,对吗?

The solution : 解决方案

$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;
    }
}

Your wrong assumption is that you think you can find any item from array of regexps in a single string with preg_grep , but it's not right. 错误的假设是您认为可以使用preg_grep在单个字符串中preg_grep数组中的任何项,但这是不对的。 Instead, preg_grep searches elements of array, which fit one single regexp. 相反, preg_grep搜索适合单个正则表达式的数组元素。 So, you just used the wrong function. 因此,您只是使用了错误的功能。

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

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