So you’re using the default WordPress video shortcode in the editor, right?
If so, there’s no need to filter the whole content, especially that markup for the video would be already rendered and is quite complicated:
<div style="width: 960px;" class="wp-video"><!--[if lt IE 9]>
<script>document.createElement('video');</script><![endif]-->
<video class="wp-video-shortcode" id="video-160186-1" width="960" height="600" preload="metadata" controls="controls">
<source type="video/mp4" src="https://wordpress.stackexchange.com/questions/300917/YOUR_VIDEO_URL" />
<a href="https://wordpress.stackexchange.com/questions/300917/YOUR_VIDEO_URL">YOUR_VIDEO_URL</a>
</video>
</div>
So instead of struggling with overcomplicated regex, you could use the wp_video_shortcode
filter. Then it gets easy:
function change_video_markup_to_amp( $output, $atts, $video, $post_id, $library ) {
/*
change output only on 'post' post type, you might wanna get
rid of this if you want to change video markup everywhere
on your site
*/
if ( ! 'post' === get_post_type( $post_id ) ) {
return $output;
}
/*
get video data, you can also check other $atts array
keys for different video formats, by default you'll find:
'mp4', 'm4v', 'webm', 'ogv', 'flv'.
*/
$video_url = ! empty( $atts['mp4'] ) ? $atts['mp4'] : '';
$height = ! empty( $atts['height'] ) ? $atts['height'] : '';
$width = ! empty( $atts['width'] ) ? $atts['width'] : '';
// return default shortcode output if no video url is found
if ( empty( $video_url ) ) {
return $output;
}
// now put the amp markup together
$amp_output = sprintf( '<amp-video controls width="%1$d" height="%2$d" layout="responsive"><source src="https://wordpress.stackexchange.com/questions/300917/%3$s" /></amp-video>', absint( $width ), absint( $height ), esc_url( $video_url ) );
return $amp_output;
}
add_filter( 'wp_video_shortcode', 'change_video_markup_to_amp', 10, 5 );