Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: How do I truncate a string while preserving words?

by bart (Canon)
on May 11, 2007 at 11:39 UTC ( [id://614877]=note: print w/replies, xml ) Need Help??


in reply to Re: How do I truncate a string while preserving words?
in thread How do I truncate a string while preserving words?

You needn't cut it if the string is not longer than maxlength. Just return the original string then.
return substr($string, 0, rindex($string, ' ') - 1);
I'd cut it on any whitespace, or at least, in front of the last partial word, like this:
$string =~ s/\s*[\w\-]*$/.../; return $string;
I'm assuming that a hyphen is a part of a word. Your idea may differ from mine.

p.s. Hmm, that'll leave any trailing nonword/nonspace characters, for example punctuation characters, intact, making the string just one character too long.

Perhaps this is better?

$string =~ s/\s*(?:[\w\-]+|\W)$/.../;
or
$string =~ s/\s*[\w\-]+$/.../ or $string =~ s/\s*\W$/.../;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://614877]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-16 13:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found