You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何移除字符串中括号内的百分比数值

移除字符串中带百分比的括号内容,保留非百分比括号

需求说明

  • 原始字符串:orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)
  • 期望输出:orange, blue (2.1), red yellow, red-blue
  • 原方法preg_replace('/[%]/', '', $raw)仅移除百分号,无法满足移除整个带百分比括号内容的需求

解决方案

使用精准匹配带百分比括号的正则表达式,配合后续空格清理,即可实现需求:

正则表达式逻辑

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

  • \(:转义匹配左括号
  • \d+:匹配至少一位整数
  • (?:\.\d+)?:非捕获组,匹配可选的小数部分(如.1、.21),?表示该部分可省略
  • %:匹配百分号
  • \):转义匹配右括号

PHP代码示例

$raw = "orange (43%), blue (2.1) (55%), red yellow (77%), red-blue (80%)";
// 移除所有带百分比的括号内容
$temp = preg_replace('/\(\d+(?:\.\d+)?%\)/', '', $raw);
// 清理多余空格,确保格式整洁
$result = preg_replace('/\s+/', ' ', trim($temp));
// 统一逗号后仅保留一个空格
$result = preg_replace('/,\s+/', ', ', $result);

echo $result; // 输出:orange, blue (2.1), red yellow, red-blue

内容的提问来源于stack exchange,提问作者maxs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 08:42:40