如何从字符串的开头和结尾修剪<br>,空格和&nbsp

Joh*_*ohn 1 php regex preg-replace

我正在尝试从字符串的开头和结尾组合对<br>or <br />,空白和&nbsp;的修剪。

有一些类似的问题(在这里这里),但是我无法在PHP中使用全部3个工具。

目前我有这个;#(^(&nbsp;|\s)+|(&nbsp;|\s)+$)#需要与此结合:/(^)?(<br\s*\/?>\s*)+$/但不知道如何实现。我正在使用PHP preg_replace。

任何帮助将是巨大的,谢谢。

voo*_*ooD 5

试试这个代码。

<?php

$test_cases = array(
    "<br>&nbsp; spaces and br at the beginning&nbsp;",
    "<br /> spaces and br with / at the beginning &nbsp;",
    "<br> <br /> more examples &nbsp;",
    "&nbsp; even more tests <br />",
    "<br/> moaaaar <br> &nbsp;",
    "&nbsp;<br> it will not remove the <br> inside the text <br />&nbsp;"
);

$array = preg_replace('#^(<br\s*/?>|\s|&nbsp;)*(.+?)(<br\s*/?>|\s|&nbsp;)*$#i', '$2', $test_cases);

foreach($array as $item) {
    echo htmlspecialchars($item) . "<br>";
}

?>
Run Code Online (Sandbox Code Playgroud)

测试用例几乎可以自我解释。

编辑:

使用大型复杂字符串时,以前的功能出现问题。我也只是想把弦的末端修剪掉对我有用

preg_replace('#(<br\s*/?>)$#i', '', $string);