Re: strip out repeated ocurrence of a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



>
> a certain string can contain the following information:
>>
>> $string =
>> 'hi{value1;value2}bye{value1;value3}hi{value1;value4}hi{value1;value2}bye{value1;value2}';
>>
>> What I want is to be able to get this result:
>>
>> $string =
>> 'hi{value1;value2}bye{value1;value3}hi{value1;value4}bye{value1;value2}';
>>
>> (the order of appearance doesn't matter)
>>
>
> Assuming the duplicate segments are identical.....
> I'd use explode() and convert the string to an array. Use "}" for the
> delimiter.
> Then use array_unique()
> And then use implode() to restore the string.
>

Really nice solution indeed :D I didn't know array_unique() (well, that's
not entirely true, I had read about it once or twice, but didn't remembered
it).

Anyway, I remembered after I sended the mail that the order DO matter, but
that is just reversing an array :)
Just for the record, the applied code is:

$string =
implode('}',array_reverse(array_unique(array_reverse(explode('}',$string)))));

First, an explode of the string to create an array, than I reverse it so
that the last ocurrence of the repeated part will always be last, after that
I apply array_unique, de-reverse it and implode it all back together as a
string.

Result?
input:
hi{value1;value2}bye{value1;value3}hi{value1;value4}hi{value1;value2}bye{value1;value2}

output:
bye{value1;value3}hi{value1;value4}hi{value1;value2}bye{value1;value2}


Thank you very much !


@Ashley: It must be done in PHP, because it should run in any environment.
But thanks anyway, any help is apreciated: you just saw that there was a
much easier way than trying to use regular expressions or str_replace when
using arrays is considerably faster (especially because the $string won't be
a few bytes, it could range from ~5 bytes up to ~300+ KiB).

Greetings!

-- 
Mailed by:
UnReAl4U - unreal4u
ICQ #: 54472056
www1: http://www.chw.net/
www2: http://unreal4u.com/

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux