Php compare strings and return common values

前端 未结 3 1720
被撕碎了的回忆
被撕碎了的回忆 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)
    
    0 讨论(0)
  • 2020-12-21 10:03

    You want to do an explode() on each list to separate them into arrays, then use array_intersect() to find the common words in both arrays.

    0 讨论(0)
  • 2020-12-21 10:06

    You can use explode and array_intersect maybe?

    Demo here & here

    <?php
    
      function common($str1,$str2,$case_sensitive = false)
      {
        $ary1 = explode(' ',$str1);
        $ary2 = explode(' ',$str2);
    
        if ($case_sensitive)
        {
          $ary1 = array_map('strtolower',$ary1);
          $ary2 = array_map('strtolower',$ary2);
        }
    
        return implode(' ',array_intersect($ary1,$ary2));
      }
    
      echo common('Product Name - Blue','Blue Green Pink Black Orange');
    

    Returns "Blue";

    EDIT Updated it to include a case-insensitive version if you'd like it.

    0 讨论(0)
提交回复
热议问题