![](/img/trans.png)
[英]What is the simplest way to search a string for a substring matching a key in an associative array in 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.