You have just a little mistake in your preg_match, instead of this:
if ( preg_match('/(year=\$matches|monthnum=\$matches)/', $rewrite) ) {
do this:
if ( preg_match('/(year=\$matches|monthnum=\$matches\/)/', $rewrite) ) {
I was looking for a solution to clean a lot of rules, this source is useful: https://wpreset.com/remove-default-wordpress-rewrite-rules-permalinks/
My final code is this, it can be customized allowing more or less rules:
add_filter( 'rewrite_rules_array', function ( $rules ) {
foreach ( $rules as $rule => $rewrite ) {
// remove most stock rewrite rules
if ( preg_match( '/(wp-json|feed|attachment|archives|trackback|comment|author|year|search|category|embed|tag|register|page\/)/', $rule ) ) {
unset( $rules[$rule] );
}
// remove year and month rules
if ( preg_match('/(year=\$matches|monthnum=\$matches\/)/', $rewrite) ) {
unset( $rules[$rule] );
}
}
// uncomment these 2 lines to check the result, open the permalink page
// echo nl2br( var_export( $rules, true ) );
// die;
return $rules;
});