Correct regex for wp_embed_register_handler

Just few notes here:

  • We have to be careful using % within sprintf() to avoid confusion with the placeholders. Try to remove the CSS styles.

  • It’s sometimes easier to use the # or ~ delimiters in regular expressions, instead of the / delimiter.

  • Since you have the (players.brightcove.net/) as the first match, it might not match this assumption:

    $account  = esc_attr( $matches[1] );
    

    Try instead:

    #https?://players\.brightcove\.net/([^/]+)/([^/]+)/index\.html\?videoId=([\d]+)#
    

This seems to work in the content editor:

add_action( 'init', function()
{
    wp_embed_register_handler( 
       'brightcove', 
       '#https?://players\.brightcove\.net)/([^/]+)/([^/]+)/index.html\?videoId=([\d]+)#', 
       'wp_embed_handler_brightcove' 
    );
} );

where wp_embed_handler_brightcove() is the callback function defined by @jgraup above.

Here’s a related answer I worked on recently.

Playing with PHPVerbalExpressions

@jgraup mentioned the library PHPVerbalExpressions – “PHP Regular expressions made easy”.

Here’s an attempt to use it:

$regex = new \VerbalExpressions\PHPVerbalExpressions\VerbalExpressions();

$regex->removeModifier( 'm' )
//      ->startOfLine()
      ->then( 'http' )
      ->maybe( 's' )
      ->then( '://players.brightcove.net/' )
      ->anythingBut( "https://wordpress.stackexchange.com/" )
      ->then( "https://wordpress.stackexchange.com/" )
      ->anythingBut( "https://wordpress.stackexchange.com/" )
      ->then( '/index.html?videoId=' )
      ->add( '([\d]+)' );
//      ->endOfLine();

This generates the following pattern:

/(?:http)(?:s)?(?:\:\/\/players\.brightcove\.net\/)(?:[^\/]*)(?:\/)(?:[^\/]*)(?:\/index\.html\?videoId\=)([\d]+)/

or if we expand it:

/
   (?:http)
   (?:s)?
   (?:\:\/\/players\.brightcove\.net\/)
   (?:[^\/]*)
   (?:\/)
   (?:[^\/]*)
   (?:\/index\.html\?videoId\=)
   ([\d]+)
/

We would have to adjust the matched keys accordingly with $matches.

Leave a Comment