preg_replace() wins
<?php
function benchmark($callback){
echo sprintf('%-30s: ', $callback);
$t = microtime(true);
foreach(range(1, 10000) as $n){
call_user_func($callback);
}
echo (microtime(true)-$t)."\n";
}
function implode_explode_filter(){
implode('-', array_filter(explode('-', '--this-is-my---string---')));
}
function preg_replace_trim(){
preg_replace('/-+/', '-', trim('--this-is-my---string---', '-'));
}
function brant(){
$parts = explode("-",'--this-is-my---string---');
for($i=0;$i<count($parts);$i++) {
if (strlen($parts[$i]) < 1) {
unset($parts[$i]);
}
}
reset($parts);
$string = implode("-",$parts);
}
function murze_bisko(){
$string = "--this-is-my---string---";
while (strpos($string, "--") !== false) {
$string = str_replace("--", "-", $string);
}
$string = trim($string, '-'); # both of their answers were broken until I added this line
}
benchmark('implode_explode_filter');
benchmark('preg_replace_trim');
benchmark('brant');
benchmark('murze_bisko');
# Output
# implode_explode_filter : 0.062376976013184
# preg_replace_trim : 0.038193941116333
# brant : 0.11686086654663
# murze_bisko : 0.058025121688843
?>