How to deal with long continuous strings with a PHP function

May 26, 2009    annoying long strings forum function messaging php split string wordwrap

An annoying problem when developing a messaging system or a forum is that users often decide to be childish.
Spamming it with the following sort of message.

"pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"

Now you can set "overflow:auto;" in your css property of the element which will deal with it well enough if the string contains a space.
However it will not deal with the problem of the above style spam/childish message if it does not contain a space, or a string within a message which does contain spaces does not or is similar to the above message.
What youll find probably if your looking at this is that the message makes the element stretch and or exceeds the elements width and basically makes a right mess of your page layout.

I have developed a work around for it below:

function one_wordwrap($string,$width){
  $s=explode(" ", $string);
  foreach ($s as $k=>$v) {
    $cnt=strlen($v);
    if($cnt>$width) $v=wordwrap($v, $width, " ", true);
      $new_string.="$v ";
  }
  return $new_string;
}

if(isset($_POST['submit'])){
$msg = htmlentities($_POST['msg'], ENT_QUOTES);
//send the posted msg to the function to check for long strings.
//you must define a width suitable for the maximum width a string can be in your desired element.
$msg = one_wordwrap($msg,50);

//go on to do whatever you may wish with the wrapped $msg variable.
}

Wallah you will now have a function which gets rid of annoying longs strings, by simply putting a space at the set width intervals you specified. You could change this so that it puts a new line in with either "br n". The reason I put a space in it, is with the space it allows the containers css properties of "overflow:auto;" to adjust the lines which I find works really well for my in-game messaging system.

Hopefully this is useful to someone else


blog comments powered by Disqus