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>
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";
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"
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you wilcoxon
David
Sorry if I didn't explain what I was after clearly enough
David
Sorry if I didn't explain what I was after clearly enough
Do this in two steps.
Open in new window