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
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)
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.
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.