Tipem
February 27, 2010, 7:54pm
1
Hi,
Somebody posted this on my web site:
Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
How can I “disable” this type of shouting? i.e.,
This!!!
to This!
Would it be best to divide the string into an array (explode() with spaces) and process each word individually? Or… what? I want to make sure I do this efficiently, too.
Any suggestions are welcomed.
Thanks in advanced.
$string = "Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
$newstring = '';
$last = '';
$repititions = 0;
$max_repititions = 2;
for ($i = 0; $i < strlen($string); $i++) {
if ($string{$i} == $last) {
$repititions++;
if ($repititions < $max_repititions)
$newstring .= $string{$i};
} else {
$last = $string{$i};
$repititions = 0;
$newstring .= $string{$i};
}
}
echo $string . "\
" . $newstring;
Output:
Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Noo!!
Don’t set max-repititions to 1 or you’ll change the word “cartoon” to “carton”.
Another possibility:
function RemoveExcessiveCharacters($String, $Limit = 3){
$ReplaceString = str_repeat('\\1', $Limit);
return preg_replace('/(.)' . $ReplaceString . '+/i', $ReplaceString, $String);
}
echo RemoveExcessiveCharacters('NNnNnNoooOooOooooOO!!!!!!!', 2);
//output: NNOO!!