Extracting returns out of an input text fields

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
AGISB
Forum Contributor
Posts: 422
Joined: Fri Jul 09, 2004 1:23 am

Extracting returns out of an input text fields

Post by AGISB »

Here is my problem. I need to display the input of an text input field in a table that is limited to a certain size.

I got space for 12 lines with 30 chars each. So now i need to count the chars and when a return is used I need to determine how many chars I have to deduct for the shorter line.

At this point I am kind of pulling a blank in my head which is frustrating because I feel the solution is so easy.

I hope some of you can point me in the right direction as it seems I have to take a little time off to get my head thinking again ;)
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

This function may help you...

Code: Select all

// textwrap 1.1 Brian Moon <brian@phorum.org>
  // This code is part of the Phorum project <http://phorum.org>

  // $String     The string to be wrapped.
  // $breaksAt   How many characters each line should be.
  // $breakStr   What character should be used to cause a break.
  // $padStr     Allows for the wrapped lines to be padded at the begining.
  
  function textwrap ($String, $breaksAt = 30, $breakStr = "\n", $padStr="") {

    $newString="";
    $lines=explode($breakStr, $String);
    $cnt=count($lines);
    for($x=0;$x<$cnt;$x++){
      if(strlen($lines[$x])>$breaksAt){
        $str=$lines[$x];
        while(strlen($str)>$breaksAt){
          $pos=strrpos(chop(substr($str, 0, $breaksAt)), " ");
          if ($pos == false) {
            break;
          }
          $newString.=$padStr.substr($str, 0, $pos).$breakStr;
          $str=trim(substr($str, $pos));
        }
        $newString.=$padStr.$str.$breakStr;
      }
      else{
        $newString.=$padStr.$lines[$x].$breakStr;
      }
    }
    return $newString;

  } // end textwrap()
Post Reply