Forum Moderators: coopster
For anyone that may want it:
$str = "The The the Hello Truck Hello The the Fantastic bear";
<?php
function remove_duplicate($str)
{
$a = explode(" ",$str);
$b = count($a);
$j = strtolower($a[0]);
$k="";
for ($i=1;$i<=$b;$i++)
{
if (strtolower($j)!=strtolower($a[$i])) { $k .= $j." "; }
$j = $a[$i];
}
return $k;
}
// will return "the Hello Truck Hello the Fantastic bear"
?>
$str = "The The the Hello Truck Hello The the Fantastic bear";
$pattern = "/\b([\w'-]+)(\s+\\1)+/i";
$replacement = "$1";
print preg_replace($pattern, $replacement, $string);
A bit complex but with a bit of study you'll see how it works ... nicely ;)
I was interested to see if it could also compete in terms of parsing time, so i did a little test
<?php
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
function removeDouble($str)
{
$words = explode(" ", $str);
$output = "";
foreach ($words AS $word)
{
if (!isset($oldWord) ¦¦ strtolower($oldWord)!= strtolower($word))
{
$output .= $word." ";
$oldWord = $word;
}
}
return substr($output, 0, -1);
}
function removeDoublePreg($str)
{
$pattern = "/\b([\w'-]+)(\s+\\1)+/i";
$replacement = "$1";
return preg_replace($pattern, $replacement, $str);
}
$str = "The The the Hello Truck Hello The the Fantastic bear";
$timeStart = getmicrotime();
echo removeDouble($str)." : ".(getmicrotime() - $timeStart)."<br>\n";
$timeStart = getmicrotime();
echo removeDoublePreg($str)." : ".(getmicrotime() - $timeStart)."<br>\n";
?>
The result:
The Hello Truck Hello The Fantastic bear : 0.000283002853394
The Hello Truck Hello The Fantastic bear : 0.0001380443573
Twice as fast, not bad ;-)
Especially if you take into account it works actually better because of the word-boundary thing (and not only with spaces)
Although I see no improvement on my case (small text up to 100 words, function is used once in page), it will do me good to experiment with the newly found knowledge.
Thanks again coopster
Checking string for consecutive alpha numerics [webmasterworld.com]
You'll have to modify it to meet your needs -- let us know if you have any trouble.