DelphiFAQ Home Search:

Force long strings to break up for better formatting


comments4 comments. Current rating: 5 stars (1 votes). Leave comments and/ or rate it.


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?


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;

Content-type: text/html


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
2008-08-05, 23:21:35
anonymous from India  
Nice work , good job

2009-01-01, 09:11:46
anonymous from Saudi Arabia  
qssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss sssssssssssqssssssssssssssssssssssssssssssss ssssssssssssssssssssssssssssss



NEW: Optional: Register   Login
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, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

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.

photo Add a picture: