Home>

I want to ambiguously search array values ​​with multiple conditions in CakePHP 2.

$array = array('carrot','pumpkin','onion');
$search = array('nin','kabo');
// desired result =>array('carrot','pumpkin');
I want to know if there is a matching value.
What I tried
$array = array('carrot','pumpkin','onion');
$search = array('/^nin/','/^Kabo/');
array_intersect($search,$array);
preg_grep($search,$array);

Neither of them returned any results.
I'm wondering if I can only use loops as a last resort
I would like to know if there are other methods.
Thank you.

This is my first question.
If there are any deficiencies in the post, I would like to ask a professor.

  • Answer # 1

    preg_grepThe first argument of must be a string type.

    PHP: preg_grep-Manual

    If you can match the regular expressionpreg_grep('/nin|kabo/', $array)If you can make it like this, you can get the expected result.

    So $searchimplodeUse to join.

    $array = ['carrot','pumpkin','onion'];
    $search = ['Nin','Kabo']];
    $searchRegex ='/' .implode('|', $search) .'/';
    preg_grep($searchRegex, $array);

    If $search is matched by an external input, the characters that have special meaning in the regular expression (/Or()) Will break the regular expression, so it's better to multiply it by preg_quote if you haven't done any preprocessing.

    $quotedSearch = array_map('preg_quote', $search);
    $searchRegex ='/' .implode('|', $search) .'/';
    preg_grep($searchRegex, $array);

    PHP: implode-Manual
    PHP: array_map-Manual
    PHP: preg_quote-Manual

  • Answer # 2

    There are similar questions in the past, so why not take a look here?
    https://stackoverflow.com/questions/6278

Related articles