...

View Full Version : Delete repeated string from string?



htcilt
01-26-2010, 06:21 PM
Hi,

Is there a function to remove repetitions of a string within another string?
I know strpos() can be used to test if there is a match, and substr_count can be used to count the number of repetitions, but I cant find anything to delete the repetitions.

For example:


$haystack = "hello world, 123, hello world";

should read:

hello world, 123

kbluhm
01-26-2010, 06:56 PM
function remove_repeats( $string, $needle )
{
if ( FALSE !== strpos( $string, $needle ) )
{
$string = explode( $needle, $string );
$string = array_shift( $string ) . $needle . implode( '', $string );
}
return $string;
}




$string = 'hello world, 123, hello world, 456, hello world, 789, hello world';

echo remove_repeats( $string, 'hello world' ); // hello world, 123, , 456, , 789,

As you can see from the return value, additional processing will need to take place.

htcilt
01-27-2010, 09:46 AM
Thanks ever so much. That's perfect!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum