5

我一直在 PHP 手册中四处寻找,但找不到任何可以满足我要求的命令。

我有一个包含键和值的数组,例如:

$Fields = array("Color"=>"Bl","Taste"=>"Good","Height"=>"Tall");

然后我有一个字符串,例如:

$Headline = "My black coffee is cold";

现在我想知道是否有任何数组 ($Fields) 值与字符串 ($Headline) 中的某处匹配。

例子:

Array_function_xxx($Headline,$Fields);

将给出结果为真,因为“bl”在字符串 $Headline 中(作为“Black”的一部分)。

我问是因为我需要性能......如果这是不可能的,我只会制作自己的功能......

编辑- 我正在寻找类似 stristr(string $haystack , array $needle);

谢谢

解决方案- 我想出了他的功能。

function array_in_str($fString, $fArray) {

  $rMatch = array();

  foreach($fArray as $Value) {
    $Pos = stripos($fString,$Value);
    if($Pos !== false)
      // Add whatever information you need
      $rMatch[] = array( "Start"=>$Pos,
                         "End"=>$Pos+strlen($Value)-1,
                         "Value"=>$Value
                       );
  }

  return $rMatch;
}

返回的数组现在有关于每个匹配单词的开始和结束位置的信息。

4

2 回答 2

5

这应该有助于:

function Array_function_xxx($headline, $fields) {
    $field_values = array_values($fields);
    foreach ($field_values as $field_value) {
        if (strpos($headline, $field_value) !== false) {
            return true; // field value found in a string
        }
    }
    return false; // nothing found during the loop
}

将函数的名称替换为您需要的名称。

编辑:

好的,替代解决方案(可能提供更好的性能,允许不区分大小写的搜索,但需要 $fields 参数中的正确值)是:

function Array_function_xxx($headline, $fields) {
    $regexp = '/(' . implode('|',array_values($fields)) . ')/i';
    return (bool) preg_match($regexp, $headline);
}
于 2011-05-08T13:20:00.117 回答
1

http://www.php.net/manual/en/function.array-search.php 这就是你要找的

来自 php.net 的示例

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
于 2011-05-08T13:07:15.560 回答