Php compare strings and return common values

前端 未结 3 1729
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 09:37

I have tried to find other posts/information on this and none of them seem to work - although I\'m sure this is a simple task.

I have two strings, and I would like t

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 09:43

    A solution would be to split your strings into two arrays of words -- using explode(), for instance :

    $string1 = "Product Name - Blue";
    $string2 = "Blue Green Pink Black Orange";
    
    $arr1 = explode(' ', $string1);
    $arr2 = explode(' ', $string2);
    

    Note that explode() is a basic solution ; you might want to use something a bit more complex, like preg_split(), which allows for more specific delimiters.


    And, then, to use array_intersect() on those arrays, to find out which words are present in both :

    $common = array_intersect($arr1, $arr2);
    var_dump($common);
    


    Which, in this case, would give :

    array
      3 => string 'Blue' (length=4)
    

提交回复
热议问题