【问题标题】:PHP removing html tags from stringPHP从字符串中删除html标签
【发布时间】:2013-02-24 21:18:21
【问题描述】:

我有字符串:

<p justify;"="">Vers­lo cent­rai Lie­tu­vos ne­kil­no­ja­mo­jo turto plėt­ros aso­cia­ci­jos kon­kur­se  ...</p>

想要移除标签

<p justify;"=""></p>

我的代码:

$content = strip_tags($text, '<p>');

但我得到空字符串:string(0) "",我做错了什么?

【问题讨论】:

    标签: php html


    【解决方案1】:

    试着这样写

    $content = strip_tags($text);
    

    或者你可以用这样的正则表达式来做:

    $content = preg_replace('/<[^>]*>/', '', $text);
    

    通过这个$content = strip_tags($text, '&lt;p&gt;');,您允许在字符串中使用&lt;p&gt; 标记。

    更多信息请查看链接http://php.net/manual/en/function.strip-tags.php

    【讨论】:

    • 它不起作用。我刚刚在我的盒子上测试了它,第一个无与伦比的报价就是问题所在。即使那个愚蠢的分号也适用于 strip_tags,只要他没有第一个引号......
    • @MihaiIorga Ya 同意你的看法。可能是拼写错误。
    【解决方案2】:

    由于 HTML 格式不正确,您可能需要编写自己的正则表达式来删除标签,或者在尝试删除标签之前清理 HTML。

    你可以试试这个来删除所有“看起来像”标签的东西:

    $str = preg_replace("/<.*?>/", " ", $str);
    

    【讨论】:

    • 真的吗?为什么 wordpress 会使用不匹配的引号?
    • 这对我有用。 strip_tags 只将标签转换为其他字符
    【解决方案3】:

    由于您的 HTML 格式不正确,您可以选择 preg_replace() 方法:

    $text = '<p justify;"="">Vers­lo cent­rai Lie­tu­vos ne­kil­no­ja­mo­jo turto plėt­ros aso­cia­ci­jos kon­kur­se ... </p>';
    $content = preg_replace('/<[^>]*>/', '', $text); 
    var_dump($content);
    // string(108) "Vers­lo cent­rai Lie­tu­vos ne­kil­no­ja­mo­jo turto plėt­ros aso­cia­ci­jos kon­kur­se ... "
    

    Codepad Example

    strip_tags() docs 上它说:因为 strip_tags() 实际上并不验证 HTML,部分或损坏的标签可能导致删除比预期更多的文本/数据。

    第二个参数也是$allowable_tags

    【讨论】:

      【解决方案4】:

      这将删除所有内容 - 标签、ascii、换行符,但纯文本:

      strip_tags(preg_replace('/<[^>]*>/','',str_replace(array("&nbsp;","\n","\r"),"",html_entity_decode($YOUR_STRING,ENT_QUOTES,'UTF-8'))));
      

      【讨论】:

      • 这在删除 'UTF-8' 后对我有用,因为第二个参数需要是整数
      【解决方案5】:

      这将替换所有 html 标签, https://regex101.com/r/jM9oS4/4

      preg_replace('/<(|\/)(?!\?).*?(|\/)>/',$replacement,$string);
      

      【讨论】:

        【解决方案6】:

        从 PHP 7.4.0 开始,strip_tags() 也可以接受带有允许标签的数组,

        然后这个:

        <?php
        
        $html = '<div id="my-div"><p>text<strong><a href="#link"></a></strong></p></div>';
        
        echo strip_tags($html, ['p', 'a']); //accept p and a tags
        

        返回这个:

        <p>text<a href="#link"></a></p>
        

        请注意,只有不允许的标签已被删除。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-05
          相关资源
          最近更新 更多