I have two stings:
$var_x = "Depending structure";
$var_y = “Depending on the structure of your array ";
Can you please tell me how can I found out, how many words in var_x is in var_y? In order to do that, I did the following:
$pieces1 = explode(" ", $var_x);
$pieces2 = explode(" ", $var_y);
$result=array_intersect($pieces1, $pieces2);
//Print result here?
But this didn't show many how many of var_x words are in var_y
Using explode()
to split the given string to words is wrong. World is not perfect and you can't make sure each word will be separated with a space.
See the following lines:
"This is a test sentence"
- 4 words from explode, "test sentence" is a single word.
Above examples are just to show that using explode()
is plain wrong. Use str_word_count()
$var_x = "Depending structure";
$var_y = "Depending on the structure of your array ";
$pieces1 = str_word_count($var_x, 1);
$pieces2 = str_word_count($var_y, 1);
$result=array_intersect(array_unique($pieces1), array_unique($pieces2));
print count($result);
This will (int) 2, and you will see that your explode() method returns the same value. But in different and complex cases, above method will give correct word count (Also note the array_unique()
use)