doumu5662 2014-02-24 19:29
浏览 123
已采纳

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

I'm trying to combine trimming of <br> or <br />, whitespaces and &nbsp;'s from the start and end of a string.

There are a few similar questions (here and here), but I couldn't get all 3 working in PHP.

Currently I have this; #(^(&nbsp;|\s)+|(&nbsp;|\s)+$)# needing combining with this: /(^)?(<br\s*\/?>\s*)+$/ but have no idea how to accomplish it. I'm using a PHP preg_replace.

Any help would be great, thanks.

  • 写回答

2条回答 默认 最新

  • dongzhong5833 2014-02-24 20:35
    关注

    Try this code.

    <?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>";
    }
    
    ?>
    

    Test cases are pretty much self explanatory.

    edit:

    I was having issues with the previous function when using large complex strings. Also I just wanted the end of the string trimmed this worked for me

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部