$re = '/(<h([1-3]{1})[^>]*?(?! id)(?:id=\"([^\"]*)\"[^>]*)?>)(.*)<\/h\2>|<!--nextpage-->/';
$str = '<h1>Test</h1>
<h1 id="test">Test</h1>
<h2 test="testattr" id="id">Test</h2>
<h3 id="id" test="test">Test</h3>
<h3 test="test" id="test" test="test">TEST</h3>
<h4></h4>
test
sdlfkdslf
<table>
h1
<!--nextpage-->';
$subst = "\1";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php