dongpu1881 2014-08-20 23:08
浏览 42
已采纳

如何从字符串中删除除反引号中包含的标记之外的所有HTML标记?

I'm using PHP's strip_tags() function to strip tags from a string. For example:

$text = strip_tags( $text );

My aim is to strip all tags unless the tags happen to be contained inside backticks. If tags are contained inside backticks, I don't want to strip them.

My first thought was to try using the second parameter of strip_tags(). This will let me specify allowable tags which are not to be removed. For example, strip_tags( $text, '<strong>'). However, this doesn't quite do what I'm looking for.

How can I strip all HTML tags from a string except tags that happen to be contained inside backticks?

Ref: http://php.net/manual/en/function.strip-tags.php

  • 写回答

2条回答 默认 最新

  • drg17404 2014-08-20 23:34
    关注

    To back my comment with an answer, something like:

    function strip($input)
    {
        preg_match_all('/`([^`]+)`/', $input, $retain);
    
        for($i = 0; $i < count($retain[0]); $i++)
        {
            // Replace HTML wrapped in backticks with match index.
            $input = str_replace($retain[0][$i], "{{$i}}", $input);
        }
    
        // Strip tags.
        $input = strip_tags($input);
    
        for($i = 0; $i < count($retain[0]); $i++)
        {
            // Replace previous replacements with relevant data.
            $replace = $retain[1][$i];
    
            // Do some stuff with $replace here - maybe check that it's a tag
            // you're comfortable with else use htmlspecialchars(), etc.
            // ...
    
            $input = str_replace("{{$i}}", $replace, $input);
        }
    
        return $input;
    }
    

    With a test:

    echo strip("Hello <strong>there</strong>, what's `<em>`up`</em>`?");
    // Output: Hello there, what's <em>up</em>?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP