Hello. Regulars for me - the dark forest. And no matter how much I tried to understand the principle of their actions, nothing happened. In general, you need to make a regular list to delete all attributes of tags except for certain ones. For example, there is a string

$string = '<a href="site.com" height="150" width="30" style="display:block" class="visible">ссылка</a>'; 

you need to remove all attributes from it except for href one regular schedule. Is it possible? Maybe someone has a ready-made expression for this?

  • and use the html parser, they all wrote for you there - splash58
  • I only need in one place to remove all attributes except one. I don’t think that it’s appropriate to connect any libraries - Al Mr
  • Well DOMDocument is part of the language itself. In order not to delete everything, you can create a new tag and transfer only the href and the contents of the tag to it - Mike

1 answer 1

From the point of view of the right decision, you definitely need to use DOMDocument::loadHTML , but if you don’t have time / desire to dig, you can use the code :

 <?php $string = '<a href="site.com" height="150" width="30" style="display:block" class="visible">ссылка</a>'; $string = preg_replace("/<([az][a-z0-9]*)(?:[^>]*(\shref=['\"][^'\"]*['\"]))?[^>]*?(\/?)>/i",'<$1$2$3>', $string); echo $string;