3v4l.org

run code in 500+ PHP versions simultaneously
<?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);

preferences:
45.23 ms | 1174 KiB | 5 Q