使用regex在数组键中查找字符串

时间:2016-11-16 12:50:52

标签: php regex

您好,

问题1:

我需要一个像这样的翻译(近似意义)函数,

$translated_array = array(
    "(.*) Car(.*)" => "is_a_Araba", // "Araba" mean car in english. İts mean this ( in regex ) string mean car.
    "(.*) Apple(.*)" => "is_a_Elma" // "Elma" mean apple in english. İts mean this ( in regex ) string mean apple.
);

有一个字符串,如下所示:

  

“1。Apple,真棒。”

我需要调用这样的函数;

function_name("1. Apple, it is awesome.", $translated_array) 
this return : "is_a_Elma".

function_name("1. Car, it is awesome.", $translated_array)
this return : "is_a_Araba".

问题2:

$translated_array = array(
    "Car name: (.*), (.*) offers." => "This car name is $1, have $2 offers."
);

İn功能:

function_name("Car name: Bugatti, 5 offers.", $translated_array)
this return : "This car name is Bugatti, have 5 offers.".

我的试用

我知道这是我的问题的解决方案,但我需要比这个功能更快。像array_regex(“Car name:Bugatti,5 offers。”,$ translated_array)(例子)

所以,我需要不循环字符串的所有值。 (有1000 +翻译价值。)

    foreach($translated_array as $key => $value):
        if(preg_match('/'.$key.'/',$mystring)): return $value; break; endif;
        continue;
    endforeach;

1 个答案:

答案 0 :(得分:0)

您可以创建一个小函数来搜索与正则表达式和每个数组索引的匹配,然后在找到匹配项时返回该值。这些方面的东西:

function arrayFindKey($expr, array $array) {
  foreach ($array as $key => $value) {
    if (preg_match($expr, $key)) {
      return $value;
    }
  }
}

$array = array(
  "1. Apple, it is awesome." => "is_a_Elma",
  "1. Car, it is awesome." => "is_a_Araba",
);
print arrayFindKey("/(.*) Apple(.*)/", $array);

我猜你也可以尝试使用单个字符串来搜索匹配,执行以下操作:

function arrayFindKey($expr, array $array) {
  // each key is separated by a '#' character
  $keys = '#' . implode('#', array_keys($array)) . '#' ;
  $matches = [];
  // if a match is found then index 1 will hold the key
  if (preg_match('/#(' . $expr . ')#/', $keys, $matches)) {
     return $array[$matches[1]];
  }
}

请注意,您需要排除#字符,因为它用作每个数组键之间的分隔符:

print arrayFindKey("[^#]+Apple[^#]+", $array);