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:
$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]
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:
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.
This is actually very easy to do …
[
: Match[
s*
: Match a whitespace 0 or more timesyouku
: Match youkus*
: 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]
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);
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.