0

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.

Nagri
  • 3,008
  • 5
  • 34
  • 63

2 Answers2

3

That's because $ is interpreted as the delimiter of your regex. You should use a simple str_replace instead. The signature is exactly the same:

str_replace($match[0], $variable_value_array, $form_body);

If you desperately wanted to use preg_replace you 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 through preg_quote, otherwise the $ will be treated as an end-of-string anchors:

$patterns = array();
foreach($match[0] as $value)
    $patterns[] = '/'.preg_quote($value, '/').'/';

And then use $patterns instead 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.

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
1

Try str_replace instead of preg_replace its faster and much appropriate for your use case

Anshul
  • 5,378
  • 2
  • 19
  • 18