DelphiFAQ Home Search:

Force long strings to break up for better formatting

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

I have to display text that comes from an external source in a rather narrow column on a web page. I use an HTML table for that and allow it to WRAP. However, sometimes the input text contains very long strings like URLs that cannot be wrapped. The input is out of my control. How can I display such long strings properly?

Answer:

You need to parse the string and if there is a substring longer than what you can tolerate, you need to look for special characters like / where you can break it up.
You can use the subroutine posted below and call it with two arguments, the string that needs to be parsed and the estimated maximum word length that you can display.

# samle call:
#   $txt = force_breaks_in_string ('this-is-a-long-string-with-no-spaces-at-all', 20);
# 20 = max substring length without spaces
# returns the string with spaces inserted
sub force_breaks_in_string {
  local ($s, $MAXL) = @_;

  $MAXL = 25;
  $word = '';
  for ($i=length($s)-1;$i;$i--) {
    $ch = substr($s,$i,1);
    if ($ch eq ' ') {
      $word = '';
    }
    else {
      $word = $ch . $word;
      if (length($word) > $MAXL) {
        if (!($word =~ s/([^w])/$1 /)) {
          $word = substr($word, 0, $MAXL/2) . ' ' . substr($word, $MAXL/2+1);
        }
        substr($s,$i,length($word)-1) = $word;
        $word = '';

      }
    }

  }

  return $s;
}

Comments:

2007-11-15, 02:33:00
anonymous from Italy  
there are some my less, but works perfectly, thanks
2007-11-15, 02:33:21
anonymous from Italy  
there are some my less, but works perfectly, thanks

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.