如何使用preg_split处理<br>标签?现有代码无法解析该标签求解决
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:
- It captures the content inside the
<>(in this case,br) and adds it as an extra element to your result array. - While the
Umodifier 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:
<brfollowed 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

