Regular expression to replace markup with iframe

I’m building a simple function to embed videos in WordPress. I want to read the post content and replace [youku: xxAAAJFSK] with an iframe: <iframe src="http://player.youku.com/embed/xxAAAJFSK"></iframe>

I’m guessing I should use a regular expression to do the replacement but can’t seem to find the correct one… I tried:

Read More
$pattern = '/youku.com/([^/]*)/i';
if (preg_match($pattern, $content, $matches)){
  $id_video = $matches[1];
  return "<iframe src='http://player.youku.com/embed/" . $id_video . "></iframe>";
}

This just breaks my site though..

Extra points if you manage to let me set the width and height using something like [youku: xxAAAJFSK width:400 height:400]

Related posts

Leave a Reply

3 comments

  1. Are you fixed to that syntax? If not, you’d be best looking at the WordPress Shortcode API and following their style. That would take a lot of the hard work out of it for you as the system would handle the argument parsing. For example:

    // [youku vid="xxAAAJFSK" width="400" height="400"]
    function youku_func( $atts ) {    
        return "<iframe src='http://player.youku.com/embed/" . $atts['vid'] . " width='" . $atts['width'] . "' height='" $atts['height'] . "'></iframe>";
    }
    add_shortcode( 'youku', 'youku_func' );
    

    You would probably want to expand this to include default values for width and height or remove them if they’re not given as arguments.

  2. This is actually very easy to do …

    • [: Match [
    • s* : Match a whitespace 0 or more times
    • youku : Match youku
    • s* : Match a whitespace 0 or more times
    • : : Match :
    • s* : Match a whitespace 0 or more times
    • ([^]]*) : Match anything except ] 0 or more times and group it
    • ] : Match ]
    • You may even use the i modifier for case insenstive matching.

    Regex: [s*youkus*:s*([^]]*)]
    Replace: <iframe src="http://player.youku.com/embed/$1"></iframe>
    PHP code: $output = preg_replace('#[s*youkus*:s*([^]]*)]#i', '<iframe src="http://player.youku.com/embed/$1"></iframe>', $input);

  3. Unless you’re doing this for educational purposes, don’t reinvent the wheel.

    There are a lot of youku-enabled WordPress plugins already.

    Edit: If you want to roll your own, I’d suggest looking at one of the existing working plugins and tailoring their implementation to suit your needs.