take this string as an example: "will see you in London tomorrow and Kent the day after tomorrow".
How would I convert this to an associative array that contains the keywords as keys, whilst preferably missing out the common words, like this:
Array ( [tomorrow] => 2 [London] => 1 [Kent] => 1)
Any help greatly appreciated.
The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.
Answer: Use the PHP array_values() function You can use the PHP array_values() function to get all the values of an associative array.
I would say you could :
explode
preg_split
array_filte
r to only keep the lines (i.e. words) you want
array_count_values
on the resulting list of words
EDIT : and, just for fun, here's a quick example :
First of all, the string, that gets exploded into words :
$str = "will see you in London tomorrow and Kent the day after tomorrow";
$words = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);
var_dump($words);
Which gets you :
array
0 => string 'will' (length=4)
1 => string 'see' (length=3)
2 => string 'you' (length=3)
3 => string 'in' (length=2)
4 => string 'London' (length=6)
5 => string 'tomorrow' (length=8)
6 => string 'and' (length=3)
7 => string 'Kent' (length=4)
8 => string 'the' (length=3)
9 => string 'day' (length=3)
10 => string 'after' (length=5)
11 => string 'tomorrow' (length=8)
Then, the filteting :
function filter_words($word) {
// a pretty simple filter ^^
if (strlen($word) >= 5) {
return true;
} else {
return false;
}
}
$words_filtered = array_filter($words, 'filter_words');
var_dump($words_filtered);
Which outputs :
array
4 => string 'London' (length=6)
5 => string 'tomorrow' (length=8)
10 => string 'after' (length=5)
11 => string 'tomorrow' (length=8)
And, finally, the counting :
$counts = array_count_values($words_filtered);
var_dump($counts);
And the final result :
array
'London' => int 1
'tomorrow' => int 2
'after' => int 1
Now, up to you to build up from here ;-)
Mainly, you'll have to work on :
Have fun !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With