doumu5662 2014-02-25 03: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-25 04: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条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)