ThePHPUnicorn
ThePHPUnicorn

Reputation: 619

PHP removing subsequent occurrences of a word in a string, how would I do this?

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

Answers (2)

Glavić
Glavić

Reputation: 43552

Like you said :

  1. explode string to array
  2. remove duplicates
  3. implode back to string

Code:

function short($v) {
    $v = trim(preg_replace('~\s+~', ' ', $v)); # just to clear extra spacing
    $v = explode(' ', $v);
    $v = array_unique($v);
    return implode(' ', $v);
}

Example;

$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

Iakov Mishchenko
Iakov Mishchenko

Reputation: 116

<?php
$arr = explode(' ', $str);
$arr = array_unique($arr);
$str = implode(' ', $arr);

Upvotes: 0

Related Questions