Becky Becky - 7 months ago 11
PHP Question

Match array value to a part of a string

I got an array and a string. I want to match the string to any part of the array values and add the matching values into

$newAr


$mood = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');
$str = "re";
$newAr = array();


How can I get all array values which has the
$str
value anywhere in it into the new array
$newAr
?

I'm expecting:

$newAr[] = array('green')
$newAr[] = array('red')


I tried
if (stripos($mood, $str) !== false) { }
but does not do what I expect.

Answer

Here's one simple way:

$newAr = preg_grep("/$str/", $mood);

If you want it case-insensitive, for example RE, re, Re or rE then use the i modifier "/$str/i".

To have a multi-dimensional array as you show, it would be easy with array_map():

$newAr = array_map(function($v) { return (array)$v; }, $newAr);

Or from your comment to key with match:

$newAr = array_map(function($v) { return array('match'=>$v); }, $newAr);

To get the JSON format that you are expecting you would need to re-index the array:

echo json_encode(array_values($newAr));

So to put it all together:

$newAr = array_values(array_map(function($v) {
                                   return array('match'=>$v);
                                },
                                preg_grep("/$str/i", $mood)));

And after all of that, this would have been simpler:

foreach($mood as $value) {
    if(stripos($value, $str) !== false) {
        $newAr[] = array('match'=>$value);
    }
}