Prevent posting of long strings

You know the problem from weblog’s, forums and guestbook’s: Extra long strings with more than “x” same characters in order. The result is an element width which will distort your website. This function takes care of this kind of string (for example multiple chars or explanation marks). The formatted string is be shortened to the amount of characters you specify.

Try our convert long strings demo to seen how it works.

<?php 
function prevent_long_strings($post, $limit = 3) {
 $word_array = explode(" ", $post);
 $opti_string = "";
 foreach ($word_array as $val) {
 if (preg_match("/(.)\\1{".$limit.",}/", $val)) {
 $char_array = preg_split("//", $val);
 $check = 0;
 for ($i = 0; $i < count($char_array); $i++) {
 if ($char_array[$i] == $char_array[$i-1]) {
 if ($check < $limit - 1) {
 $new_word[] = $char_array[$i];
 }
 $check++;
 } else {
 $new_word[] = $char_array[$i];
 $check = 0;
 }
 }
 $opti_string .= implode("", $new_word)." ";
 unset($new_word);
 } else {
 $opti_string .= $val." ";
 }
 }
 return $opti_string;
}
// Example:
echo prevent_long_strings("Hello, can you heeeeeeeeaaaaaaaar meeeeeeeeeeeee !!!!!!!!!!!!!!!!!!! !!!!!!!!", 3);
// is converted to "Hello, can you heeeaaar meee !!! !!!"

Leave a Reply

Your email address will not be published. Required fields are marked *