Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
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 exploiting the Monastery: (10)
As of 2015-01-30 00:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My top resolution in 2015 is:

















    Results (246 votes), past polls