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

PHP如何提取文本中被%%包裹的字符串(排除单个%干扰)

这问题我熟!你遇到的是正则匹配时的边界问题——那些半吊子的%(比如单独的6%或者带空格的% commission)干扰了正确匹配。解决办法是用精准的正则表达式,只匹配被%完整包裹、中间是合法变量名的字符串。

解决方案:精准正则匹配合法的%包裹变量

核心思路是限定%之间的内容必须是无空格的合法标识符(比如字母、数字、下划线,这是变量名的常见规则),这样就能自动过滤掉那些不完整的%场景。

正则表达式说明

用这个正则就能精准匹配:

/%([a-zA-Z0-9_]+)%/g
  • %:匹配开头的百分号
  • ([a-zA-Z0-9_]+):捕获中间的内容,要求是1个以上的字母、数字或下划线(排除空格和其他无关字符)
  • %:匹配结尾的百分号
  • /g:全局搜索,找出所有符合条件的结果

代码示例(JavaScript)

const inputText = "The total % commission on property mentioned above is 6% of %purchase_amount% (purchase price) = %total_commission%...";
const variableRegex = /%([a-zA-Z0-9_]+)%/g;
const result = [];
let match;

// 循环捕获所有匹配项
while ((match = variableRegex.exec(inputText)) !== null) {
  // 如果需要带%的完整字符串,就push match[0];如果只要变量名,push match[1]
  result.push(match[0]);
}

console.log(result);
// 输出:["%purchase_amount%", "%total_commission%"]

代码示例(Python)

如果你用Python处理,写法更简洁:

import re

input_text = "The total % commission on property mentioned above is 6% of %purchase_amount% (purchase price) = %total_commission%..."
matches = re.findall(r'%([a-zA-Z0-9_]+)%', input_text)

# 要带%的话,用这个正则:r'%(?:[a-zA-Z0-9_]+)%'
# matches = re.findall(r'%(?:[a-zA-Z0-9_]+)%', input_text)

print(matches)
# 输出(不带%):['purchase_amount', 'total_commission']

灵活调整

如果你的变量名允许其他字符(比如连字符-),只需要修改正则里的字符集即可:

/%([a-zA-Z0-9_-]+)%/g

这样就能完美避开那些干扰项,只提取你需要的完整变量字符串啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:49:02