Lars Vegas :
A string look like this:
$string = 'Super this is a test this is a test';
Output should be:
Super
I am trying to remove duplicate words completly from a string. What I have found is:
echo implode(' ',array_unique(explode(' ', $string)));
but here is the output:
Super this is a test
Thank you for a easy way to do this.
treyBake :
That's because array_unique()
reduces duplicates to one value:
Takes an input array and returns a new array without duplicate values.
src
You need to loop the array first (though can imagine a lot of creative array_filter/array_walk stuff possibly):
$string = 'Super this is a test this is a test';
# first explode it
$arr = explode(' ', $string);
# get value count as var
$vals = array_count_values($arr);
foreach ($arr as $key => $word)
{
# if count of word > 1, remove it
if ($vals[$word] > 1) {
unset($arr[$key]);
}
}
# glue whats left together
echo implode(' ', $arr);
And as a function for general project-use:
function rm_str_dupes(string $string, string $explodeDelimiter = '', string $implodeDelimiter = '')
{
$arr = explode($explodeDelimiter, $string);
$wordCount = array_count_values($arr);
foreach ($arr as $key => $word)
{
if ($wordCount[$word] > 1) {
unset($arr[$key]);
}
}
return implode($implodeDelimiter, $arr);
}
# example usage
echo rm_str_dupes('Super this is a test this is a test');
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=220124&siteId=1