dongyikong6207 2016-08-30 14:12
浏览 50
已采纳

正则表达式替换括号之间的html标签

I need to replace html tags placed between parenthesis. Following is my code. Any help would be appreciated.

$string  = '<table><tr>Hello{<strong><br/>name<br/></strong>}</tr></table>';
echo preg_replace("/\{<.*?>\}/","",$string);

Required output is

<table><tr>Hello name</tr></table>
  • 写回答

2条回答 默认 最新

  • douyue8364 2016-08-30 14:37
    关注

    You can not do this using a simple regex alone, but you can use a regex to find the paranthesis blocks as follwing

    function process_paranthesis($match) {
      return strip_tags($match[1]);
    }
    
    $string  = '<table><tr>Hello { <strong>name</strong>}</tr></table>';
    echo preg_replace_callback("/\{([^\}]*)\}/", "process_paranthesis",$string);
    

    The RegEx was modified to just find all {...}-blocks and we use preg_replace_callback(), which calls a function that computes the string that the match is to be replaced to. The parameter $match of the callback function contains information about the match in various ways. $match[0] contains the whole text of the match and $match[1] contains the text within the first paranthesis within the match. The function strip_tags() is then used within the callback function, to remove all HTML-Tags. This is a predefined function and should be used instead of reinventing the wheel.

    The RegEx is constructed as following:

    1. A match starts with a { and ends with a }; we need to escape it so we use \{...\}.
    2. We want to process everything, but the surrounding { and }, so we put round paranthesis inside: \{(...)\} and will then get the whole content within the curly braces as $match[1] without further need to remove those curly braces by using other string functions.
    3. We want to allow all characters between the { and } except for the } itself; we use [^\}], which matches every kind of character but }; and we want to allow multiple of them, resulting in: [^\}]*

    NOTE: .* is greedy. So, if we just use .* instead of [^\}]* we would get weird results in case there are multiple blocks of curly braces. The match would start at the first opening { and end at the last } within the string and would containing all blocks and everything between it. This would match like this: "Text {in first} something between {and second one}. And some more." -- But we want it to match like this: "Text {in first} something between {and second one}. And some more.", right?

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

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体