Link to home
Start Free TrialLog in
Avatar of trevor1940
trevor1940

asked on

perl: Truncate a string to a maximum length

Hi

How do I truncate a string to a maximum length but at a white space?
I know substr(0,15) would work but I don't want to end in the middle of a word

the result of the code bellow should be $ShortString  = "Lorem ipsum" because the 15th character is the "l" in dolor!

In reality the length  would be 150 but it's easier to count 15 characters

Once I have $ShortString  this will form part of a URL do I need escape it?

So
 

<a href="$http://example.com?foo=bar&mystring=$ShortString>My Link</a>
 

my $LongString="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas fermentum, nunc in vestibulum lobortis, sapien dui aliquam risus, vitae tincidunt risus augue id dolor. Nullam.";

my $len = length($LongString);

print "Lenth of LongString = $len\n";

my $ShortString;

if ($len > 15){
    ($ShortString) = $LongString =~ m/^(.*[15])?<=\b/
}
else{
    $ShortString = $LongString
}
print "ShortString = $ShortString\n";

Open in new window

Avatar of David Favor
David Favor
Flag of United States of America image

If I understand what your asking...

Do this in two steps.

# Truncate the string at character 150
$str = substr($str,0,150);

# Trim any trailing whitespace, along with any non-whitespace, if any non whitespace exists
$str =~ s/\s+[^\s]*//o;

Open in new window

Avatar of trevor1940
trevor1940

ASKER

David
you missed the s from
$str =~ s/\s+[^\s]*//o;

However using a string length of 15  it gives

ShortString = Lorem dol

Not  $ShortString  = "Lorem ipsum"
Sure enough! Just edited the code for future views.
Since your initial question was unclear about all use cases, you'll have to modify the solution to match all your cases.
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you wilcoxon

David
Sorry  if I didn't explain what I was after clearly enough