DelphiFAQ Home Search:
General :: Programming :: perl
General questions about perl.


This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.
Recommended links on this topic:
Featured Article

Force long strings to break up for better formatting


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;

Generated 12:01:38 on Oct 27, 2020