Find embed, add atttribute

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
hwdesign
Forum Newbie
Posts: 9
Joined: Fri Dec 18, 2009 4:40 am

Find embed, add atttribute

Post 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!
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Find embed, add atttribute

Post 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
hwdesign
Forum Newbie
Posts: 9
Joined: Fri Dec 18, 2009 4:40 am

Re: Find embed, add atttribute

Post 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!
hwdesign
Forum Newbie
Posts: 9
Joined: Fri Dec 18, 2009 4:40 am

Re: Find embed, add atttribute

Post by hwdesign »

Worked like a charm. Thanks!
Post Reply