在 PHP 中将 space 替换为 preg_replace?

Removing substituing space with a preg_replace in PHP?

<a param1="false" class="param2" id="id#12" href="#1">toto</a>

我在 PHP 中制作了 preg_replace 以删除 [=33= 中的某些参数] 文字:

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

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

我得到这个 html link:

<a href="#1">toto</a>

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

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

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

按以下方式更改您的常规,

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

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

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

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

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

你可以试试这个:

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

Regex101