PHP Array values in string?

Max Kielland picture Max Kielland · May 8, 2011 · Viewed 9.9k times · Source

I have been looking around for a while in the PHP manual and can't find any command that does what I want.

I have an array with Keys and Values, example:

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

Then I have a string, for example:

$Headline = "My black coffee is cold";

Now I want to find out if any of the array ($Fields) values match somewhere in the string ($Headline).

Example:

Array_function_xxx($Headline,$Fields);

Would give the result true because "bl" is in the string $Headline (as a part of "Black").

I'm asking because I need performance... If this isn't possible, I will just make my own function instead...

EDIT - I'm looking for something like stristr(string $haystack , array $needle);

Thanks

SOLUTION - I came up with his function.

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

The returning array now have information on where each matched word begins and ends.

Answer

Tadeck picture Tadeck · May 8, 2011

This should help:

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
}

Replace name of the function with what you need.

EDIT:

Ok, alternative solution (probably giving better performance, allowing for case-insensitive search, but requiring proper values within $fields parameter) is:

function Array_function_xxx($headline, $fields) {
    $regexp = '/(' . implode('|',array_values($fields)) . ')/i';
    return (bool) preg_match($regexp, $headline);
}