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);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.6
string(132) "<h2 class="xyz" id="foo">foo</h2> <p>ksfdgdfhd</p> <h2 id="bar-baz">bar baz</h2> <div>psggffb</div> <h2 id="ggggg">ggggg</h2> gsgged" array(3) { [0]=> array(2) { [0]=> string(3) "foo" [1]=> string(3) "foo" } [1]=> array(2) { [0]=> string(7) "bar baz" [1]=> string(7) "bar-baz" } [2]=> array(2) { [0]=> string(5) "ggggg" [1]=> string(5) "ggggg" } }

preferences:
79.43 ms | 1174 KiB | 4 Q