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

如何使用preg_split处理<br>标签?现有代码无法解析该标签求解决

Fixing preg_split to Split on <br> Tags and Get Your Desired Result

Let’s break down why your current code isn’t working as expected, then fix it to get exactly the output you want: 0 => 'test', 1 => 'end'.

Why Your Current Code Fails

Your regex /<(.*)>/U combined with PREG_SPLIT_DELIM_CAPTURE does two things you don’t need:

  1. It captures the content inside the <> (in this case, br) and adds it as an extra element to your result array.
  2. While the U modifier makes the match ungreedy, the regex is too broad—it would split on any HTML tag, not just <br>.

Correct Solution

To split the string on <br> tags and exclude the tag itself from the result, you can use a simpler regex without capturing groups (or adjust it to handle common <br> variations if needed).

Basic Case (Exact <br> Match)

If you only need to split on the exact <br> tag:

$html = "test<br>end";
$result = preg_split('/<br>/', $html);
print_r($result);

This will output exactly what you want:

Array
(
    [0] => test
    [1] => end
)

Handling Common <br> Variations

If you need to account for self-closing tags like <br/> or tags with whitespace like <br >, use a regex that matches those cases:

$html = "test<br/>end<br   >another line";
$result = preg_split('/<br\s*\/?>/', $html);
print_r($result);

This regex targets:

  • <br followed by any number of whitespace characters (\s*)
  • Optional forward slash (\/?)
  • Closing >

The output will be:

Array
(
    [0] => test
    [1] => end
    [2] => another line
)

Key Changes That Make This Work

  • We removed PREG_SPLIT_DELIM_CAPTURE, so the <br> tag (the delimiter) is excluded from the result array.
  • The regex is now specific to <br> tags (and their variations), so it won’t accidentally split on other HTML elements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:41:00