[Solved] How to replace only a specific word from the end of the string in PHP? [closed]


Based on the conditions you mentioned you can do something like below. Find the word count and then check is home available in the string and then find the index of the house . So then you can check does that index match to last index of the word array (count($wordArray)) - 1)

$string1 = 'this is my house';
    $string2 = 'this house is mine';
    $wordArray = explode(' ', $string1); // make the array with words
    //check the conditions you want 
    if (in_array('house', $wordArray) && (array_search('house', $wordArray) == (count($wordArray)) - 1)) {
        $string1 = str_replace('house', 'dog', $string1);
    }
    echo $string1;

solved How to replace only a specific word from the end of the string in PHP? [closed]