OK, I've been trying to figure this one out for a while, but I can't seem to get it right. I need to delete the last occurrence of a non-consecutive, duplicate word/phrase from the END of a string. For example, I want
Love in My Antonia Love in
and
Love in My Antonia Love
to become
Love in My Antonia
I have tried countless patterns without success. The closest I have gotten to success is this:
preg_replace('/\b(\w{2,})\b(?=.*?\\1)\W*/', ''
That deletes the first occurrence (rather than the last), rendering:
in My Antonia Love (ORIGINAL: "Love in My Antonia Love")
and
My Antonia Love in (ORIGINAL: "Love in My Antonia Love in")
Please help! :)
UPDATE (Nov. 9, 2:00 PM, PST): I should have clarified that—if at all possible—I would like the solution to remain in the simple, 1-line, compact format that I showed in my example:
preg_replace('/\b(\w{2,})\b(?=.*?\\1)\W*/', ''
My example already works almost perfectly, except that it deletes the first match instead of the last. I was hoping that someone could modestly manipulate my existing code so that it deletes the last match (at the end of the string) instead of the first occurrence. Is that more complicated than I thought?
Previously, I came up with a version that finds two consecutive, duplicate words/phrases anywhere in a string and replaces them with one:
preg_replace('~\b([\S \w]{3,})\K\b(?:\s*\1)+~', '',
This makes "pizza pizza" become "pizza" and "I walked to the store I walked to the store" become "I walked to the store." That's great, and I have already incorporated that solution. Now, secondarily, I also need "Pizza is the best pizza" to become "Pizza is the best." Similarly, "Sheep dogs are awesome pets dogs are" should become "Sheep dogs are awesome pets." So, basically, it does not matter where in the string the first occurrence appears; all that matters is that the occurrence at the END OF THE STRING gets deleted. I hope this brings more clarity.