Something like
$string =~ s/^\s+/ /; ($string) = $string =~ /^\s?(.{0,50}\w+)/; if (length $string > 50) { $string =~ s/\w+$//; }
The first line removes all multiple spaces and replaces them with a single space. The second line ignores a leading space then capures 50 characters and if a word extends past the 50 word boundary it catches the rest of the word as well. The if/then block removes that last word if the length of the string is over 50 characters. Keep in mind if someone enters 51 (or more) characters in a row with no spaces then $string will have an empty value at the end of this block of code.

Edit: In response to your reply  $string =~ s/^\s+/ / breaks down as:
=~ apply the regular expression on the right of this operator to the string on the left.
s/^\s+/ / substitute one or more spaces at the beginning of the string with a single space. It would have been better in this case to leave out the space between the last two slashes, but I'm used to using s/\s+/ /g which replaces all multiple spaces with a single space.

The code I posted will do the two things you mentioned as well as cut the string down to 50 characters or less without truncating the last word (If just a couple letters of the last word goes over the 50 character limit then the whole word goes) You can't depend on the truncating being done on client side. There are too many ways of getting around client side content control.

John

In reply to Re: Searching Strings for Characters by Cyrnus
in thread Searching Strings for Characters by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.