I am trying to replace few words from a huge string with preg_replace()
using it like this :
preg_replace($match[0], $variable_value_array, $form_body)
Here $match[0] is an array with value in it in the form like:
$contacts-firstname$
$contacts-lastname$
$contacts-mobile$
$leads-leadstatus$
$leads-noofemployees$
and $variable_value_array is also an array with values in it like :
Linda
William
(091) 115-9385
Value Not Present
Value Not Present
and $form_body is a really long string.
The function is replacing the values of $form_body but instead of replacing the whole $contacts-firstname$ with Linda it is replacing only contacts-firstname with Linda making it like $Linda$. What should i do to replace both the $ sigh’s as well ?
Thanks.
That’s because
$is interpreted as the delimiter of your regex. You should use a simplestr_replaceinstead. The signature is exactly the same:If you desperately wanted to use
preg_replaceyou need to do two things. Firstly, you need to wrap every array element in explicit delimiters (/is kind of the standard choice). And also you need to run every array element throughpreg_quote, otherwise the$will be treated as an end-of-string anchors:And then use
$patternsinstead of$match[0]. But that is only intended as a nice-to-know if you ever actually need to use an array of literal search-strings inside a more complex pattern.