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

PHP:批量替换字符串中多次出现的特殊字符间内容

替换字符串中多次出现的方括号内特殊内容

嘿,这个需求其实很常见,用正则表达式配合替换函数就能完美解决!我给你用两种常用语言举例子,思路都是通用的~

核心思路

我们需要:

  1. 匹配字符串中所有[xxx]格式的内容
  2. 把每个方括号里的内容(比如special content type 3)映射到对应的目标值(比如wi-xxx)
  3. 全局替换所有符合条件的内容

JavaScript实现示例

// 你的原始字符串
const originalStr = '<div><small>static content</small><small>[special content type 3]</small> <small>static content</small><small>[special content type 4]</small></div>';

// 定义特殊内容和目标值的映射表,你可以根据需求修改
const contentMap = {
  "special content type 3": "wi-special-icon-3",
  "special content type 4": "wi-special-icon-4"
};

// 执行全局替换
const replacedStr = originalStr.replace(/\[(.*?)\]/g, (fullMatch, contentInside) => {
  // 如果映射表里有对应值就替换,没有就保留原内容(避免丢失)
  return contentMap[contentInside] || fullMatch;
});

console.log(replacedStr);

代码解释

  • 正则/\[(.*?)\]/g:g表示全局匹配所有符合的内容,(.*?)是非贪婪捕获,确保只匹配单个方括号内的内容(不会从第一个[一直匹配到最后一个])
  • 替换函数的两个参数:fullMatch是整个匹配的字符串(比如[special content type 3]),contentInside是捕获到的方括号内的文本
  • 用contentMap[contentInside]获取对应替换值,找不到就返回原匹配内容,保证兼容性

Python实现示例

如果你用Python,思路完全一致:

import re

original_str = '<div><small>static content</small><small>[special content type 3]</small> <small>static content</small><small>[special content type 4]</small></div>'

content_map = {
    "special content type 3": "wi-special-icon-3",
    "special content type 4": "wi-special-icon-4"
}

def replace_handler(match_obj):
    content = match_obj.group(1)
    # 同样,找不到对应值就保留原内容
    return content_map.get(content, match_obj.group(0))

replaced_str = re.sub(r'\[(.*?)\]', replace_handler, original_str)
print(replaced_str)

注意事项

  • 如果方括号内的内容包含正则特殊字符(比如*、+),不用担心,我们的正则是捕获内容,这些字符不会影响匹配
  • 映射表可以动态生成,比如从后端接口获取,只需要更新映射表即可,替换逻辑不需要改动

内容的提问来源于stack exchange,提问作者i.brod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:10:01