Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Answer: How do I delete the last instance of a word from a string?

( #121981=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How do I delete the last instance of a word from a string? contributed by suaveant

substr($string,rindex($string,$word),length($word)) = '';
or, to avoid removing the last character of the string when $word is not present:
my $ri = rindex($string,$word); substr($string,$ri,length($word)) = '' if $ri > -1;

Edit by tye to incorporate reply

Comment on Answer: How do I delete the last instance of a word from a string?
Select or Download Code
Replies are listed 'Best First'.
Re: Answer: How do I delete the last instance of a word from a string?
by suaveant (Parson) on Oct 30, 2001 at 19:24 UTC
    danger pointed out that this removes the last char of the string if word is not found... if that is an issue use the following...
    my $ri = rindex($string,$word); substr($string,$ri,length($word)) = '' if $ri > -1;

                    - Ant
                    - Some of my best work - (1 2 3)

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2015-07-29 11:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (263 votes), past polls