4

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 to have some lines of code that give me the word that they have in common.

For example, I may have...

String1 = "Product Name - Blue";
String2 = "Blue Green Pink Black Orange";

And I would like to have a string only containing the value Blue. How can I do this? Thanks in advance!

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I was thinking of this, but wouldn't that only work if both instances of "blue" begin with a capital b? It sounds like he may need to create his own function to mimic array_intersect but case insensitive. EDIT: It seems you edited to account for this. Well done.
yes, the lowercase addition is useful. Do you know of any way to add the ability to check a segment of words. For example: instead of blue, match something like purple owl?
@thepristinedesign: Can you give two string examples and desired outcome?
String1 = "NVEY - Lipstick (Muted Coral Pink)"; String2 = "muted coral pink, style2, style3, etc.."; Desired outcome would be -> muted coral pink
@theprestinedesign: Is the second string always CSV?
|
3

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()`**][3] 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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.