in reply to Searching Strings for Characters

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

Replies are listed 'Best First'.
Re: Re: Searching Strings for Characters
by Anonymous Monk on Jun 04, 2002 at 04:10 UTC
    Hi i'm the poster, basically there are 2 types of things i want to fix...

    First Case:

    "(pretend there are 10 or so white spaces) some input(pretend there are 5 or so white spaces)"

    I want it to be:
    "some input"
    and also

    Second Case:

    " (pretend this is a lot of white spaces) "
    I want this to be:
    "(pretend this has no spaces in it)"


    also as a side note can you explain to me what does =~ s/^\s+/ /; means I don't get this at all, I am trying to transfer from C++ thats why I have so much trouble. Thanks again guys, you guys are the best.