在PHP中使用preg_replace删除替换空格


Removing substituing space with a preg_replace in PHP?

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

我已经做了一个preg_replacePHP删除某些参数在html文本:

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

我得到这个html链接:

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

我想在和href之间只留下一个空间,是否有可能直接在正则表达式中做到这一点?

按以下方式更改您的regular regular,

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

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

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

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

你可以试试:

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

Regex101

假设您必须在"preg_match"中使用所有的反向引用。这是您完成

的唯一方法。
$re = "/<a.*(param1='"false'"|class='"param2'"|id='"id#([^'"]+)'")/";
$text = preg_replace($re, "<a", $data->text->value);