regex php如何删除括号内的百分比值

jecbmhm3  于 2023-05-30  发布在  PHP
关注(0)|答案(2)|浏览(258)

如何删除括号内的百分比值。
示例:

<?php
$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

u5rb5r59

u5rb5r591#

您可以使用

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

并将其替换为""。参见a demo on regex101.com

dfty9e19

dfty9e192#

给你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;

相关问题