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" - 5 words from explode()
- "This is a test sentence. Not a word." - 8 words, you will get "sentence." as a word.
"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)