Sunitrams' Sunitrams' - 2 months ago 8
PHP Question

Removing substituing space with a preg_replace in PHP?

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


I have made a preg_replace in PHP to remove certain params in a html text:

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

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


I obtain this html link:

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


I would like to leave only one space beetween the and the href, is it possible to do that directly in the regex ?

Answer

Change your regular regular in the following way,

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

You need to pass \s+ in each of your component.

And change your preg_replace() function in the following way,

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

Don't replace them with space, that's it.