【问题标题】:Removing substituing space with a preg_replace in PHP?在 PHP 中用 preg_replace 删除替换空间?
【发布时间】:2016-09-25 19:50:35
【问题描述】:
<a param1="false" class="param2" id="id#12" href="#1">toto</a>

我在 PHP 中制作了一个 preg_replace 来删除 html 文本中的某些参数:

$re = "/(param1=\"false\"|class=\"param2\"|id=\"id#([^\"]+)\")/";

$text = preg_replace($re, " ", $data->text->value); 

我获得了这个 html 链接:

&lt;a href="#1"&gt;toto&lt;/a&gt;

我想在 和 href 之间只留一个空格,是否可以直接在正则表达式中这样做?

【问题讨论】:

    标签: php regex preg-replace pcre


    【解决方案1】:

    通过以下方式更改您的常规常规,

    $re = '/(param1="false"\s+|class="param2"\s+|id="id#([^\"]+)"\s+)/';
    

    您需要在每个组件中传递\s+

    并按以下方式更改您的 preg_replace() 函数,

    $text = preg_replace($re, "", $data->text->value);
    

    不要用空格替换它们,就是这样。

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      $re = "/(param1=\"false\"|class=\"param2\"|id=\"id\#([^\"]+)\")([\ ]{1,}?)/";
      $text = preg_replace($re, "", $data->text->value);
      

      Regex101

      【讨论】:

        【解决方案3】:

        假设您必须使用“preg_match”中的所有反向引用。这是你可以完成的唯一方法

        $re = "/<a.*(param1=\"false\"|class=\"param2\"|id=\"id#([^\"]+)\")/";
        $text = preg_replace($re, "<a", $data->text->value);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-03
          • 1970-01-01
          • 1970-01-01
          • 2011-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多