How to deal with long continuous strings with a PHP function

May 26, 2009

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.


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) {
    if($cnt>$width) $v=wordwrap($v, $width, " ", true);
      $new_string.="$v ";
  return $new_string;

if(isset($POST[‘submit’])){ $msg = htmlentities($POST[‘msg’], ENTQUOTES); //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 = onewordwrap($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

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.