It is very simple with the e modifier in regexp, not needed in preg_replace_callback
$str = '===Heading 3==='; echo preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/e', 'implode("", array("<h", strlen("$1"), ">$2</h", strlen("$1"), ">"));', $str);
or in this way
echo preg_replace('/(?:\n|^)(={3,6})([^=]+)(\1)/e', '"<h".strlen("$1").">$2</h".strlen("$1").">"', $str);
source share