Page 1 of 1

Find embed, add atttribute

Posted: Wed May 12, 2010 3:50 pm
by hwdesign
I use the following php to find and retrieve all embed tags. However, I'm wondering if there is a way to add the attribute wmode="opaque" to the tag before returning it...

Code: Select all

function show_thumb() {
	
	global $post, $posts;
	
	$thumb = '';
  
  	ob_start();
  	ob_end_clean();

	$output = preg_match_all('/(\<embed.*\<\/embed\>)/is', $post->post_content, $matches);
	$thumb = $matches [1] [0];
	
	if(empty($thumb)) {
	
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  		$thumb = $matches [1] [0];	
		
		if(empty($thumb)) {
		
		} else {
		
			return '<div class="thumb"><img src="'.$thumb.'" alt="thumb-'.$post->ID.'" /></div>';
		
		}
	
	} else {
		
		return '<div class="thumb">'.$thumb.'</div>';
	
  	}

}
Essentially, I find the embed and wrap it in a div so I can re-size it, and if there isn't an embed tag, I find an image. However, I want to add the attribute wmode="opaque" before returning the embed. Thanks!

Re: Find embed, add atttribute

Posted: Thu May 13, 2010 8:37 am
by ridgerunner
Try this:

Code: Select all

$re = '%<embed\b([^>]*)>(.*?)</embed>%s';
$str = preg_replace($re, '<div class="thumb"><embed wmode="opaque"$1>$2</embed></div>', $str);
Note that there are some real problems with your code. For starters, you use the greedy dot star ".*" combination which will fail to match multiple <embed> tags, You need to use the lazy version: ".*?"
see: http://www.regular-expressions.info/repeat.html#greedy

Re: Find embed, add atttribute

Posted: Thu May 13, 2010 2:41 pm
by hwdesign
Thanks, this is pretty much my only attempt at regex, so I have no idea what I'm doing.

However, I only want to get one match. This runs on a loop so it gets one match per post.

If you see any other suggestions to improving this, please let me know.

I'll give your changes a whirl and post back how it goes.

Thanks!

Re: Find embed, add atttribute

Posted: Thu May 13, 2010 3:27 pm
by hwdesign
Worked like a charm. Thanks!