如何在括号内删除百分比值的 PHP方式

huangapple go评论50阅读模式
英文:

php how to remove percentage value inside bracket

问题

`如何删除括号内的百分比数值。

示例:

$raw = "orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)";
$remove = preg_replace('/[%]/', '', $raw);
echo $remove;

结果:

orange (43), blue (2.1) (55), red yellow (77), red-blue (80)

我需要的是这样的:

orange, blue (2.1), red yellow, red-blue

英文:

How to remove the percentage value inside the bracket.

example:

<?php
$raw = "orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)";
$remove = preg_replace('/[%]/', '', $raw);
echo $remove;
?>

results:

orange (43), blue (2.1) (55), red yellow (77), red-blue (80)

What I need is like this:

orange, blue (2.1), red yellow, red-blue

答案1

得分: 2

你可以使用\s+(\d+(?:.\d+)?%),然后用""替换它。请参考regex101.com上的演示

英文:

You may use

\s+\(\d+(?:\.\d+)?%\)

And replace this with "". See a demo on regex101.com.

答案2

得分: 0

这里是代码,100%工作:

$raw = "orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)";
$raw = explode(", ", $raw);
for($a = 0; $a <= count($raw) - 1; $a++){
    $test = explode(" ", $raw[$a]);
    
    
    for($b = 0; $b <= count($test) - 1; $b++){
        if(str_contains($test[$b], '%')){
            $test[$b] = '';
        }
    }
    $result[$a] = implode(" ", $test);
    
}
$raw = implode(", ", $result);
echo $raw;
英文:

here you go, works 100%

$raw = &quot;orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)&quot;;
$raw = explode(&quot;, &quot;, $raw);
for($a = 0; $a &lt;= count($raw) - 1; $a++){
    $test = explode(&quot; &quot;, $raw[$a]);
    
    
    for($b = 0; $b &lt;= count($test) - 1; $b++){
        if(str_contains($test[$b], &#39;%&#39;)){
            $test[$b] = &#39;&#39;;
        }
    }
    $result[$a] = implode(&quot; &quot;, $test);
    
}
$raw = implode(&quot;, &quot;, $result);
echo $raw;

huangapple
  • 本文由 发表于 2023年5月28日 07:18:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定