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: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):The
0before the closing parenthesis ofsubstr_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:
References:
strripos().substr_replace().