Delete last occurrence of a non-consecutive, duplicate word/phase in a PHP string









up vote
2
down vote

favorite












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(w2,)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(w2,)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,)Kb(?: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.










share|improve this question























  • What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
    – Tim Biegeleisen
    yesterday










  • @TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
    – Jason
    yesterday














up vote
2
down vote

favorite












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(w2,)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(w2,)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,)Kb(?: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.










share|improve this question























  • What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
    – Tim Biegeleisen
    yesterday










  • @TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
    – Jason
    yesterday












up vote
2
down vote

favorite









up vote
2
down vote

favorite











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(w2,)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(w2,)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,)Kb(?: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.










share|improve this question















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(w2,)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(w2,)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,)Kb(?: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.







php regex preg-replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 23 hours ago

























asked yesterday









Jason

306




306











  • What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
    – Tim Biegeleisen
    yesterday










  • @TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
    – Jason
    yesterday
















  • What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
    – Tim Biegeleisen
    yesterday










  • @TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
    – Jason
    yesterday















What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
– Tim Biegeleisen
yesterday




What happens if the last word be a duplicate? E.g. what would Love in My Anotonia Love Love become?
– Tim Biegeleisen
yesterday












@TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
– Jason
yesterday




@TimBiegeleisen, such a situation would be an extreme outlier, so I'm not concerned. Good question, though.
– Jason
yesterday












3 Answers
3






active

oldest

votes

















up vote
1
down vote



accepted










Here you go:



$s = preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);


Test:



$s = "Love in My Antonia Love in";
$s1 = "Love in My Antonia Love";
$s2 = "Love in My Antonia Love Not On End";

echo "Original:n$sn";
echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);
echo "n";
echo "Original:n$s1n";
echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s1);
echo "n";
echo "Original:n$s2n";
echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s2);


Output:



ZC-MGMT-04:~ jv$ php -q c.php
Original:
Love in My Antonia Love in
Love in My Antonia
Original:
Love in My Antonia Love
Love in My Antonia
Original:
Love in My Antonia Love Not On End
Love in My Antonia Love Not On End


====



UPDATE:



Jason suggests slight update to address ' at the end of the word:



preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2')





share|improve this answer






















  • Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
    – Jason
    22 hours ago











  • My bad. That was only because I had another preg_replace that was conflicting.
    – Jason
    20 hours ago










  • Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
    – Jason
    20 hours ago







  • 1




    jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
    – Jason
    20 hours ago

















up vote
1
down vote













You could approach this without regular expressions, by splitting the sentence into component words and then manually checking the last two words:



$input = "Love in My Antonia Love in";
$words = preg_split("/s+/", $input);
$last = $words[count($words)-1];
$pattern = "/^(?=.*b" . $last . "b.*b" . $last . "b).*/";
if ($words[count($words) - 1] != $words[count($words) - 2] &&
preg_match($pattern, $input, $match))
array_pop($words);

$output = implode(" ", $words);
echo $input . "n" . $output;

Love in My Antonia Love in
Love in My Antonia Love





share|improve this answer


















  • 1




    You are answering your own question but not OP's one
    – splash58
    yesterday










  • @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
    – Tim Biegeleisen
    yesterday










  • I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
    – splash58
    yesterday










  • Compare with your output
    – splash58
    yesterday










  • You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
    – Tim Biegeleisen
    yesterday


















up vote
0
down vote













You need to find the longest duplicate substring first then remove it from the end of subject string. This could be done using a preg_match_all for doing a case-insensitive search then a preg_replace for omitting them:



$str = 'Love in My Antonia Love in';
preg_match_all('~(bw++(?> w++)*)(?=.*?b1)~i', $str, $matches);
$array = array_unique(array_map('strtolower', $matches[1]));
foreach ($array as $value)
$str = preg_replace("~^.*K(?<!s)s*b$value~i", '', $str);

echo trim($str); // Love in My Antonia


See live demo here






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53224175%2fdelete-last-occurrence-of-a-non-consecutive-duplicate-word-phase-in-a-php-strin%23new-answer', 'question_page');

    );

    Post as a guest






























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Here you go:



    $s = preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);


    Test:



    $s = "Love in My Antonia Love in";
    $s1 = "Love in My Antonia Love";
    $s2 = "Love in My Antonia Love Not On End";

    echo "Original:n$sn";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);
    echo "n";
    echo "Original:n$s1n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s1);
    echo "n";
    echo "Original:n$s2n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s2);


    Output:



    ZC-MGMT-04:~ jv$ php -q c.php
    Original:
    Love in My Antonia Love in
    Love in My Antonia
    Original:
    Love in My Antonia Love
    Love in My Antonia
    Original:
    Love in My Antonia Love Not On End
    Love in My Antonia Love Not On End


    ====



    UPDATE:



    Jason suggests slight update to address ' at the end of the word:



    preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2')





    share|improve this answer






















    • Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
      – Jason
      22 hours ago











    • My bad. That was only because I had another preg_replace that was conflicting.
      – Jason
      20 hours ago










    • Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
      – Jason
      20 hours ago







    • 1




      jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
      – Jason
      20 hours ago














    up vote
    1
    down vote



    accepted










    Here you go:



    $s = preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);


    Test:



    $s = "Love in My Antonia Love in";
    $s1 = "Love in My Antonia Love";
    $s2 = "Love in My Antonia Love Not On End";

    echo "Original:n$sn";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);
    echo "n";
    echo "Original:n$s1n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s1);
    echo "n";
    echo "Original:n$s2n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s2);


    Output:



    ZC-MGMT-04:~ jv$ php -q c.php
    Original:
    Love in My Antonia Love in
    Love in My Antonia
    Original:
    Love in My Antonia Love
    Love in My Antonia
    Original:
    Love in My Antonia Love Not On End
    Love in My Antonia Love Not On End


    ====



    UPDATE:



    Jason suggests slight update to address ' at the end of the word:



    preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2')





    share|improve this answer






















    • Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
      – Jason
      22 hours ago











    • My bad. That was only because I had another preg_replace that was conflicting.
      – Jason
      20 hours ago










    • Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
      – Jason
      20 hours ago







    • 1




      jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
      – Jason
      20 hours ago












    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    Here you go:



    $s = preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);


    Test:



    $s = "Love in My Antonia Love in";
    $s1 = "Love in My Antonia Love";
    $s2 = "Love in My Antonia Love Not On End";

    echo "Original:n$sn";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);
    echo "n";
    echo "Original:n$s1n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s1);
    echo "n";
    echo "Original:n$s2n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s2);


    Output:



    ZC-MGMT-04:~ jv$ php -q c.php
    Original:
    Love in My Antonia Love in
    Love in My Antonia
    Original:
    Love in My Antonia Love
    Love in My Antonia
    Original:
    Love in My Antonia Love Not On End
    Love in My Antonia Love Not On End


    ====



    UPDATE:



    Jason suggests slight update to address ' at the end of the word:



    preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2')





    share|improve this answer














    Here you go:



    $s = preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);


    Test:



    $s = "Love in My Antonia Love in";
    $s1 = "Love in My Antonia Love";
    $s2 = "Love in My Antonia Love Not On End";

    echo "Original:n$sn";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s);
    echo "n";
    echo "Original:n$s1n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s1);
    echo "n";
    echo "Original:n$s2n";
    echo preg_replace('/^b([w ]+)(.*?)b(1)$/i', '\1\2', $s2);


    Output:



    ZC-MGMT-04:~ jv$ php -q c.php
    Original:
    Love in My Antonia Love in
    Love in My Antonia
    Original:
    Love in My Antonia Love
    Love in My Antonia
    Original:
    Love in My Antonia Love Not On End
    Love in My Antonia Love Not On End


    ====



    UPDATE:



    Jason suggests slight update to address ' at the end of the word:



    preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2')






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 9 hours ago

























    answered 23 hours ago









    jancha

    4,23911533




    4,23911533











    • Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
      – Jason
      22 hours ago











    • My bad. That was only because I had another preg_replace that was conflicting.
      – Jason
      20 hours ago










    • Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
      – Jason
      20 hours ago







    • 1




      jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
      – Jason
      20 hours ago
















    • Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
      – Jason
      22 hours ago











    • My bad. That was only because I had another preg_replace that was conflicting.
      – Jason
      20 hours ago










    • Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
      – Jason
      20 hours ago







    • 1




      jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
      – Jason
      20 hours ago















    Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
    – Jason
    22 hours ago





    Your solution successfully changes "Love in My Antonia Love" to "Love in My Antonia", but it does not change "Women in Combat Units Women" to "Women in Combat Units". Any idea why?
    – Jason
    22 hours ago













    My bad. That was only because I had another preg_replace that was conflicting.
    – Jason
    20 hours ago




    My bad. That was only because I had another preg_replace that was conflicting.
    – Jason
    20 hours ago












    Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
    – Jason
    20 hours ago





    Here's my final, tweaked version that works best because it prevents accidental truncation within words AND prevents 's from being left behind when it is attached to a deleted word: preg_replace('/^b([w ]+)(.*?)bb(1)('s)*b$/i', '\1\2',
    – Jason
    20 hours ago





    1




    1




    jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
    – Jason
    20 hours ago




    jancha, you may want to edit your answer to incorporate my tweaks. It's up to you. Thanks!
    – Jason
    20 hours ago












    up vote
    1
    down vote













    You could approach this without regular expressions, by splitting the sentence into component words and then manually checking the last two words:



    $input = "Love in My Antonia Love in";
    $words = preg_split("/s+/", $input);
    $last = $words[count($words)-1];
    $pattern = "/^(?=.*b" . $last . "b.*b" . $last . "b).*/";
    if ($words[count($words) - 1] != $words[count($words) - 2] &&
    preg_match($pattern, $input, $match))
    array_pop($words);

    $output = implode(" ", $words);
    echo $input . "n" . $output;

    Love in My Antonia Love in
    Love in My Antonia Love





    share|improve this answer


















    • 1




      You are answering your own question but not OP's one
      – splash58
      yesterday










    • @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
      – Tim Biegeleisen
      yesterday










    • I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
      – splash58
      yesterday










    • Compare with your output
      – splash58
      yesterday










    • You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
      – Tim Biegeleisen
      yesterday















    up vote
    1
    down vote













    You could approach this without regular expressions, by splitting the sentence into component words and then manually checking the last two words:



    $input = "Love in My Antonia Love in";
    $words = preg_split("/s+/", $input);
    $last = $words[count($words)-1];
    $pattern = "/^(?=.*b" . $last . "b.*b" . $last . "b).*/";
    if ($words[count($words) - 1] != $words[count($words) - 2] &&
    preg_match($pattern, $input, $match))
    array_pop($words);

    $output = implode(" ", $words);
    echo $input . "n" . $output;

    Love in My Antonia Love in
    Love in My Antonia Love





    share|improve this answer


















    • 1




      You are answering your own question but not OP's one
      – splash58
      yesterday










    • @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
      – Tim Biegeleisen
      yesterday










    • I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
      – splash58
      yesterday










    • Compare with your output
      – splash58
      yesterday










    • You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
      – Tim Biegeleisen
      yesterday













    up vote
    1
    down vote










    up vote
    1
    down vote









    You could approach this without regular expressions, by splitting the sentence into component words and then manually checking the last two words:



    $input = "Love in My Antonia Love in";
    $words = preg_split("/s+/", $input);
    $last = $words[count($words)-1];
    $pattern = "/^(?=.*b" . $last . "b.*b" . $last . "b).*/";
    if ($words[count($words) - 1] != $words[count($words) - 2] &&
    preg_match($pattern, $input, $match))
    array_pop($words);

    $output = implode(" ", $words);
    echo $input . "n" . $output;

    Love in My Antonia Love in
    Love in My Antonia Love





    share|improve this answer














    You could approach this without regular expressions, by splitting the sentence into component words and then manually checking the last two words:



    $input = "Love in My Antonia Love in";
    $words = preg_split("/s+/", $input);
    $last = $words[count($words)-1];
    $pattern = "/^(?=.*b" . $last . "b.*b" . $last . "b).*/";
    if ($words[count($words) - 1] != $words[count($words) - 2] &&
    preg_match($pattern, $input, $match))
    array_pop($words);

    $output = implode(" ", $words);
    echo $input . "n" . $output;

    Love in My Antonia Love in
    Love in My Antonia Love






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    Tim Biegeleisen

    206k1379127




    206k1379127







    • 1




      You are answering your own question but not OP's one
      – splash58
      yesterday










    • @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
      – Tim Biegeleisen
      yesterday










    • I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
      – splash58
      yesterday










    • Compare with your output
      – splash58
      yesterday










    • You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
      – Tim Biegeleisen
      yesterday













    • 1




      You are answering your own question but not OP's one
      – splash58
      yesterday










    • @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
      – Tim Biegeleisen
      yesterday










    • I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
      – splash58
      yesterday










    • Compare with your output
      – splash58
      yesterday










    • You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
      – Tim Biegeleisen
      yesterday








    1




    1




    You are answering your own question but not OP's one
    – splash58
    yesterday




    You are answering your own question but not OP's one
    – splash58
    yesterday












    @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
    – Tim Biegeleisen
    yesterday




    @splash58 Just because the OP requested regex does not mean it is the best solution here. Wiktor's regex looks pretty complex, and I would not want to maintain or inherit that in an actual code base.
    – Tim Biegeleisen
    yesterday












    I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
    – splash58
    yesterday




    I want Love in My Antonia Love in and Love in My Antonia Love to become Love in My Antonia
    – splash58
    yesterday












    Compare with your output
    – splash58
    yesterday




    Compare with your output
    – splash58
    yesterday












    You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
    – Tim Biegeleisen
    yesterday





    You are interpreting "duplicate" differently than I am. I am interpreting that as meaning if the last two words are the same, then we don't replace. Maybe I'm wrong.
    – Tim Biegeleisen
    yesterday











    up vote
    0
    down vote













    You need to find the longest duplicate substring first then remove it from the end of subject string. This could be done using a preg_match_all for doing a case-insensitive search then a preg_replace for omitting them:



    $str = 'Love in My Antonia Love in';
    preg_match_all('~(bw++(?> w++)*)(?=.*?b1)~i', $str, $matches);
    $array = array_unique(array_map('strtolower', $matches[1]));
    foreach ($array as $value)
    $str = preg_replace("~^.*K(?<!s)s*b$value~i", '', $str);

    echo trim($str); // Love in My Antonia


    See live demo here






    share|improve this answer


























      up vote
      0
      down vote













      You need to find the longest duplicate substring first then remove it from the end of subject string. This could be done using a preg_match_all for doing a case-insensitive search then a preg_replace for omitting them:



      $str = 'Love in My Antonia Love in';
      preg_match_all('~(bw++(?> w++)*)(?=.*?b1)~i', $str, $matches);
      $array = array_unique(array_map('strtolower', $matches[1]));
      foreach ($array as $value)
      $str = preg_replace("~^.*K(?<!s)s*b$value~i", '', $str);

      echo trim($str); // Love in My Antonia


      See live demo here






      share|improve this answer
























        up vote
        0
        down vote










        up vote
        0
        down vote









        You need to find the longest duplicate substring first then remove it from the end of subject string. This could be done using a preg_match_all for doing a case-insensitive search then a preg_replace for omitting them:



        $str = 'Love in My Antonia Love in';
        preg_match_all('~(bw++(?> w++)*)(?=.*?b1)~i', $str, $matches);
        $array = array_unique(array_map('strtolower', $matches[1]));
        foreach ($array as $value)
        $str = preg_replace("~^.*K(?<!s)s*b$value~i", '', $str);

        echo trim($str); // Love in My Antonia


        See live demo here






        share|improve this answer














        You need to find the longest duplicate substring first then remove it from the end of subject string. This could be done using a preg_match_all for doing a case-insensitive search then a preg_replace for omitting them:



        $str = 'Love in My Antonia Love in';
        preg_match_all('~(bw++(?> w++)*)(?=.*?b1)~i', $str, $matches);
        $array = array_unique(array_map('strtolower', $matches[1]));
        foreach ($array as $value)
        $str = preg_replace("~^.*K(?<!s)s*b$value~i", '', $str);

        echo trim($str); // Love in My Antonia


        See live demo here







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered yesterday









        revo

        31.2k124679




        31.2k124679



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53224175%2fdelete-last-occurrence-of-a-non-consecutive-duplicate-word-phase-in-a-php-strin%23new-answer', 'question_page');

            );

            Post as a guest














































































            Popular posts from this blog

            Kleinkühnau

            Makov (Slowakei)

            Deutsches Schauspielhaus