<?php $text = '<h2 class="xyz">foo</h2> <p>ksfdgdfhd</p> <h2>bar baz</h2> <div>psggffb</div> <h2>ggggg</h2> gsgged'; $anchors = []; $new = preg_replace_callback('@(<h2.*?)>(.*?)<\/h2>@',function($matches) use(&$anchors) { $anchor = str_replace(' ', '-', $matches[2]); $anchors[] = [$matches[2], $anchor]; return $matches[1] . ' id="' . $anchor . '">' . $matches[2] . '</h2>'; }, $text); var_dump($new, $anchors);
You have javascript disabled. You will not be able to edit any code.