Reputation: 619
I'm pulling data, and the format in which its supplied isn't very neat. For example, the data provides something along the lines of:
But all I want to do is remove the second (and any subsequent occurrence) of repeated words, so that the string looks like:
So far, I've thought of making an array of words from the string, removing the next row where the word has already been repeated, and then building the string back from the array rows. Does anyone have any other (better) ideas of doing this? Its part of a synchronisation service which is already quite resource heavy, so making this process as efficient as possible is important.
Thanks in advance for any ideas. Muchos Appreciatos! Ste
Upvotes: 0
Views: 70
Reputation: 43552
Like you said :
function short($v) {
$v = trim(preg_replace('~\s+~', ' ', $v)); # just to clear extra spacing
$v = explode(' ', $v);
$v = array_unique($v);
return implode(' ', $v);
}
$v = 'Volkswagen Golf 2.0 TDI Golf Match';
echo short($v); # Volkswagen Golf 2.0 TDI Match
$v = ' Volkswagen Passat Passat SE ';
echo short($v); # Volkswagen Passat SE
Upvotes: 2
Reputation: 116
<?php
$arr = explode(' ', $str);
$arr = array_unique($arr);
$str = implode(' ', $arr);
Upvotes: 0