Friends have text in the form of html

 $string = " <p> some text</p> <h3>h3 text1</h3> <p> some text</p> some text <h3>h3 text2</h3> <h3>h3 text3</h3> ........ "; 

where it is necessary to replace h3 with a href as follows

How to find the value of h3 (h3 text1 | h3 text2 | h3 text3)

pass to getSlug('h3 text1') , which is ready for me, which returns a new value after some processing, and this new value is already inserted into a href="#новое значение"

  $string = preg_replace_callback( '|<h3>(.[^<]*)<\/h3>\w|', function ($matches) { $h3 = $matches[0];//подразумеваю что получил h3 целиком $last_h3_Position = strpos($h3, '</h3>');//Находим позицию закрывающего h3 (</h3>) $h3_text = substr($h3, 4 ,$last_h3_Position);//Получить текст между открывающего и закрывающего тегами //return getSlug($matches[0]); return '<a href="#'.getSlug($h3_text).'">'.$h3_text.'</a>'; }, $string ); echo $string; 

The result was hoping to get this:

 $string = " <p> some text</p> <a href='#slug1'>h3 text1</a> <p> some text</p> some text <a href='#slug2'>h3 text2</a> <a href='#slug3'>h3 text3</a> ........ "; 

help me please

How can this be realized?

  • And if you simplify the regular season to |<h3>(.*?)</h3>| and the text between the tags you have already enclosed in parentheses, and therefore is available in $ matches [1] - Mike
  • one
  • @Mike So I did everything right except the regular season? with $ matches [1] agrees, like I missed it - user216109
  • one
    Well, yes, the regulator is a bit curved, the main problem in \w which required a certain letter after </ h3>. excessive `\` hardly played a role. Well, what a crooked selection of the line between the tags, which is just replaced by matches [1] - Mike
  • @Mike Thank you very much, add as an answer so that I and others check it out :) - user216109

1 answer 1

You almost did everything right. Only the regular schedule requires a letter ( \w ) after </h3> and can be simplified a little more. As well as inside the callback function, everything that was allocated to the first parentheses is available in $matches[1] (in $matches[0] entire match).

 $string = " <p> some text</p> <h3>h3 text1</h3> <p> some text</p> some text <h3>h3 text2</h3> <h3>h3 text3</h3> ........ "; $string = preg_replace_callback( '|<h3>(.*?)</h3>|', function ($matches) { return '<a href="#'.getSlug($matches[1]).'">'.$matches[1].'</a>'; }, $string ); echo $string;