http://www.perlmonks.org?node_id=121980

Warped has asked for the wisdom of the Perl Monks concerning the following question: (strings)

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

Originally posted as a Categorized Question.

  • Comment on How do I delete the last instance of a word from a string?

Replies are listed 'Best First'.
Re: How do I delete the last instance of a word from a string?
by suaveant (Parson) on Oct 30, 2001 at 01:03 UTC
    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

      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)

Re: How do I delete the last instance of a word from a string?
by tye (Sage) on Oct 30, 2001 at 01:19 UTC
    Although I prefer the rindex/substr solution, another alternative involves regular expressions with "zero-width negative look-ahead assertions": s/\Q$word\E(?!.*\Q$word\E)//s or, if you really only want "words": s/\b\Q$word\E\b(?!.*\b\Q$word\E\b)//s
Re: How do I delete the last instance of a word from a string?
by Incognito (Pilgrim) on Nov 07, 2001 at 03:08 UTC
    tye's regex solution works well, but you may want to modify it to:
    $sentence =~ s/\b\Q$word\E\b\s+(?!.*\b\Q$word\E\b)//s;
    to elimitate the extra space that's left when the word is removed. This leaves us with:
    String: the quick brown dog jumped the doggy style dog killing doggie +eater. Result: the quick brown dog jumped the doggy style killing doggie eate +r.
    where the $word = "dog".

    (Added by tye) Note that if the last occurance of that word is also the last word of a sentence, it will have whitespace in front of it and not behind it and this regex will fail. If the last occurance of the word is unlikely to be the first word in the string, then

    $sentence =~ s/\s*\b\Q$word\E\b(?!.*\b\Q$word\E\b)//s;
    would be a better choice.
      Perhaps a slight change is necessary... Consider:

      'Go walk the dog'

      -Blake