Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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
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 rifling through the Monastery: (4)
As of 2014-08-31 08:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls