user1625155
user1625155

Reputation: 521

PHP preg_replace Calculation Not working

I am trying to create a hook, so that when the following is found within text:

level,2

It replaces it with $skill_level * $n, with the number after the comma being $n

Here is what I have:

$skill_level = 2;

$row['s_effect'] = "Long string of text that contains level,2."

preg_replace("/level,$n/",$skill_level * $n,$row['s_effect'])

I am getting a result of:

Long string of text that contains 02.

I want a result of:

Long string of text that contains 4.

For some reason it seems the calculation "$skill_level * $n" (2 * 2) is not working.

Upvotes: 0

Views: 258

Answers (1)

xdazz
xdazz

Reputation: 160843

You need to use preg_replace_callback

$skill_level = 2;
$text = "Long string of text that contains level,2.";

$ret = preg_replace_callback("/level,(\d+)/", function ($matches) use ($skill_level) {
  return $matches[1] * $skill_level;
}, $text);

Upvotes: 3

Related Questions