<(?Ph\d)(?P[^>]*)>(?P[^<]*))#i'; if ( preg_match_all( $pattern, $content, $matches, PREG_SET_ORDER ) ) { $find = array(); $replace = array(); foreach( $matches as $match ) { if ( strlen( $match['tag_extra'] ) && false !== stripos( $match['tag_extra'], 'id=' ) ) { continue; } $find[] = $match['full_tag']; $id = sanitize_title( $match['tag_contents'] ); $id_attr = sprintf( ' id="%s"', $id ); $extra = sprintf( ' #', $id ); $replace[] = sprintf( '<%1$s%2$s%3$s>%4$s%5$s', $match['tag_name'], $match['tag_extra'], $id_attr, $match['tag_contents'], $extra ); } $content = str_replace( $find, $replace, $content ); } return $content; }