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

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?

我基本上想要的是用百分比替换所有数字和/或数字,但是使用匹配来包装 类。 我不想用javascript做这个。 p>

所以这是我的字符串; p>

  $ string ='Call a 一群8只暗影野兽在目标位置从天空坠落,在5秒内造成3200%的总武器伤害,并使惊恐的敌人击中2秒。'
  code>  pre> 
 
 

这是我想要实现的一个例子; p>

  $ string ='调用一组&lt; span class =“d3-color-green”&gt; 8&lt; / 跨度&GT; 暗影野兽在目标位置从天空坠落,并且处理&lt; span class =“d3-color-green”&gt; 3200%&lt; / span&gt; 超过&lt; span class =“d3-color-green”&gt; 5&lt; / span&gt;的总武器伤害 秒和惊人的敌人击中&lt; span class =“d3-color-green”&gt; 2&lt; / span&gt; 秒。'
  code>  pre> 
 
 

我正在尝试这样做; p>

  preg_replace(“/ [  0-9] *%/“,'&lt; span class =”d3-text-green“&gt; $ 1&lt; / span&gt;',$ string); 
  code>  pre> 
 
  

唯一的问题是,这会删除数字和百分比,并将其替换为类。 我是以正确的方式还是完全离开? p> div>

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);
//          ___^    ___^