$text contains some text with multiple tags. How to find all the strings in $ text:

 <тег class="black" тут его остальные свойства>тут содержимое тега</тег> 

and replace with the contents of the tag with a newline, and write to another variable? For example:

<div class="black" id="left">левый блок</div>

to change to:

левый блок

In general, tags, contents of tags, properties, except for class, can be different.

  • one
    HTML parser you need to use. The string <div class = "black"> <b> text <i> text </ i> </ b> <div> text </ div> </ div> you will not parse with a regular schedule. - Sh4dow
  • I don’t need a parser, I normally described the task and where does <div class = "black" <b> text <i> text </ i> </ b> <div> text </ div> </ div> .. .... I have generated a clear code for which I described the task - shol

1 answer 1

The variable $string your text.

Then the line

 preg_replace('/<([^\s]+)[\s+]class="black"[^>]*>([^<]*)<\/\\1>/','\\2',$string); 

Returns the contents of any tag contained in $string with the class="black" parameter specified immediately after the opening tag.

those.

<a htrf="http://hashcode.ru" class="black">hashcode</a> will not be processed

<a class="black" href="http://hashcode.ru">hashcode</a> will return hashcode

Upd example:

next html code

 <h1 class="black">Пример</h1> <div class="black" style="color:red"> <span style="font-style:italic"> Форум </span> </div> <a class="black" href="hashcode.ru"> hashcode </a> 

Regularized, returned

 Пример <div class="black" style="color:red"> <span style="font-style:italic"> Форум </span> </div> hashcode 

those. tags with class="black" containing other tags are not processed

  • and in $ string all the tags that match the regular schedule are replaced? - shol
  • yes, all occurrences are replaced - ikoolik
  • If there are 2 nested tags, there will be fun. Diva in the diva, for example. - Sh4dow
  • Regulars will skip nested divs, as it reads the contents up to the opening bracket only when this bracket is the beginning of the closing tag for the tag with class="black" - ikoolik