View Full Version : using substr and whole words
zenweezil
07-22-2004, 04:57 AM
I have a variable for a story headline that I want to shorten to under 30 characters, but want it to end after a complete word.
So I can shorten to 30 characters with this:
$shorthead = substr ($headline, 0, 30);
But how do I modify to have it cut off after a word ends?
Any ideas?
dswimboy
07-22-2004, 04:56 PM
i would use regular expressions. something like this to chop off that last part of a word:
$headline =~ s/ \S$//;
this removes the last space followed by non-whitespace at the end of the line. if the headline is exactly 30 letters long, it will remove that last full word, however. thus, i would do something like this:
if ($shorthead = substr ($headline, 0, 30);) {
$shorthead =~ s/ \S$//;
}
zenweezil
07-22-2004, 08:02 PM
I tried this code:
$shorthead = substr ($headline, 0, 30)
$shorthead =~ s/ \S$//;
But the line $shorthead =~ s/ \S$//; made no change to the $shorthead varaible and did not chop off the broken word.
I also tried just this line to the orginal headline:
$headline=~ s/ \S$//;
But again there was no change to the $headline varaible and did not chop off at the end of a word.
I also unsuccessfully tried:
if ($shorthead = substr ($headline, 0, 30)) {
$shorthead =~ s/ \S$//;
}
Is this expression correct: $shorthead =~ s/ \S$//;
dswimboy
07-23-2004, 06:03 PM
ah! i forgot something. try adding a star, like this:
$shorthead =~ s/ \S*$//;
zenweezil
07-30-2004, 06:30 AM
I also found another way to just grab the first few words with an array:
($FirstWord, $SecondWord, $ThirdWord, $FourthWord, $FifthWord, $RestOfSentence) = split(/ /, $headline, 6) ;
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.