Preg_replace仅包含百分比的数字和/或数字

What I basically want is to replace all numbers and/or numbers with percentages, but use the matches to wrap inside a class. I don't want to do this with javascript.

So this is the string I have;

$string = 'Call a group of 8 Shadow Beasts to plummet from the sky at a targeted location dealing 3200% total weapon damage over 5 seconds and stunning enemies hit for 2 seconds.'

And here is an example of what I want to achieve;

$string = 'Call a group of <span class="d3-color-green">8</span> Shadow Beasts to plummet from the sky at a targeted location dealing <span class="d3-color-green">3200%</span> total weapon damage over <span class="d3-color-green">5</span> seconds and stunning enemies hit for <span class="d3-color-green">2</span> seconds.'

This is how I'm trying to do this;

preg_replace("/[0-9]*%/", '<span class="d3-text-green">$1</span>', $string);

The only problem is, this removes the numbers and percentages and replaces this with the class. Am I in the right way or completely off?

You are not capturing the number. To capture a specific part, you can place the regular expression inside round brackets or parentheses. The captured values can be be referenced using backreferences. For example, the portion matched by the first capturing group can be obtained using $1.

preg_replace("/([0-9]+%?)/", '<span class="d3-text-green">$1</span>', $string);

Explanation:

  • / - starting delimiter
  • ([0-9]+) - match (and capture) any digit from 0 - 9, one or more times
  • %? - match a literal % character, optionally
  • / - closing delimiter

Use a capture group:

preg_replace("/([0-9]+%)/", '<span class="d3-text-green">$1</span>', $string);
//          ___^    ___^