How to generically replace one string with another using a variable

advertisements

Problem:

I am stuck in figuring out how to add a string in a variable to a number of different strings using PHP.

Variable:

$insert = 'icon-white';

Strings are in a variable called $hyperlink:

$hyperlink = '<i class="icon-home"></i>';

Desired output:

<i class="icon-home icon-white"></i>

Any recommendations are welcome, and thanks in advance.


I honestly don't see the benefits of regex in this particular question, so I've chosen to disregard that aspect; the principal concern seems to be to insert the new string before the last " character, which can be achieved with the following:

$hyperlink = '<i class="icon-home"></i>';
$insert = ' icon-white'; // I've explicitly prefixed the new string with a space
$pos = strripos($hyperlink,'"',0);
echo substr_replace($hyperlink,$insert,$pos,0)

If you'd rather, then, for future use, here's a function that will insert a given string ($new) into another string ($haystack) before the last occurrence of a given character ($needle):

function insertBeforeLast($haystack,$needle,$new){
    if (!$haystack || !$needle || !$new){
        return false;
    }
    else {
        return substr_replace($haystack,$new,strripos($haystack,$needle),0);
    }
}

    echo insertBeforeLast('abcdefg','e','12',' ');

The 0 before the closing parenthesis of substr_replace() in the function denotes the number of characters that the newly-inserted string will overwrite in the original string.


Edited to amend the above function to explicitly offer the over-writing as an option:

function insertBeforeLast($haystack,$needle,$new, $over){
    if (!$haystack || !$needle || !$new){
        return false;
    }
    else {
        $over = $over || 0;
        return substr_replace($haystack,$new,strripos($haystack,$needle),$over);
    }
}

    echo insertBeforeLast('abcdefg','e','12',0);

References: