To find number of duplicate occurrence of the word in the string, we need to first loop through each word of the string, save it independently in an array and then if duplicate word is found then we need to increase the current count of the word value.
Let's first jump right into the example and then we will understand-
Inside the function, we first removed any extra blank space between the word using following code and also need to explode that string into an array to get an individual word-
Then, inside for() loop,
Let's first jump right into the example and then we will understand-
<?php function get_number_of_duplicate_word_count($str) { $arr = array(); $exp = explode(' ', preg_replace('/\s+/', ' ', $str)); $nm_of_words = count($exp); $html = '<table style="width:100%"><tr><th>word</th><th>count</th></tr>'; for ($i = 0; $i < $nm_of_words; $i++) { if (!array_key_exists($exp[$i], $arr)) { $html .= '<tr><td>' . $exp[$i] . '</td><td>1</td></tr>'; $arr[$exp[$i]] = 1; } else { preg_match('/<tr><td>' . $exp[$i] . '[\s\S]*?<\/tr>/', $html, $output_array); if (!empty($output_array)) { $html = str_replace($output_array[0], '<tr><td>' . $exp[$i] . '</td><td>' . (++$arr[$exp[$i]]) . '</td></tr>', $html); } } } return $html; } echo get_number_of_duplicate_word_count('php is development the best web development language language php');
Inside the function, we first removed any extra blank space between the word using following code and also need to explode that string into an array to get an individual word-
$exp = explode(' ', preg_replace('/\s+/', ' ', $str));
Then, inside for() loop,
No comments:
Post a Comment