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

如何用PHP preg_replace替换指定div内的<br>标签为空格?

解决方法:在特定div内替换
标签为空格

要实现仅在<div class="nobr">与</div>之间替换<br>为空格,使用preg_replace_callback是最可靠的方案(避免单一正则的复杂度和长度限制),具体步骤如下:

核心思路

  1. 匹配所有包含class="nobr"的div块
  2. 对每个匹配到的div内部内容,单独替换所有<br>标签(含变体)为空格
  3. 将处理后的内容重新包裹回div标签中

代码示例

$originalHtml = 'keep this<br>line break<div class="nobr"> but replace this linebreak<br>with a space</div> another<br>line <div class="nobr">and another<br/>here</div>';

$processedHtml = preg_replace_callback(
    '/<div class="nobr">(.*?)<\/div>/s',
    function($matches) {
        // 替换div内部所有<br>变体为空格
        return '<div class="nobr">' . preg_replace('/<br\s*\/?>/i', ' ', $matches[1]) . '</div>';
    },
    $originalHtml
);

echo $processedHtml;

代码说明

  • 外层正则/<div class="nobr">(.*?)<\/div>/s:
    • s修饰符让.匹配换行符,确保能捕获跨多行的div内容
    • .*?是非贪婪匹配,避免误匹配多个div块的内容
  • 回调内的正则/<br\s*\/?>/i:
    • 匹配所有常见的<br>写法:<br>、<br/>、<br />
    • i修饰符忽略大小写,兼容<BR>这类大写标签

效果验证

原内容:

keep this<br>line break<div class="nobr"> but replace this linebreak<br>with a space</div> another<br>line <div class="nobr">and another<br/>here</div>

处理后结果:

keep this<br>line break<div class="nobr"> but replace this linebreak with a space</div> another<br>line <div class="nobr">and another here</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:47:31