2

Ive got the following function wrapping all iframe's in a div class="video-container"

I want to target only iframes that contain a src beginning with src="www.youtube

Is there a way to modify this function do be more specific?

Thanks in advance.

function div_wrapper($content) {
// match any iframes
$pattern = '~<iframe.*</iframe>~';
preg_match_all($pattern, $content, $matches);

foreach ($matches[0] as $match) {
    // wrap matched iframe with div
    $wrappedframe = '<div class="video-container">' . $match . '</div>';

    //replace original iframe with new in content
    $content = str_replace($match, $wrappedframe, $content);
}

return $content;    
}
add_filter('the_content', 'div_wrapper');
user1385827
  • 325
  • 1
  • 6
  • 23
  • `if (!condition) continue;` inside the foreach as the first line. Make condition the target condition (src begins with whatever) – Patashu Feb 06 '13 at 06:09

2 Answers2

0

Perform a lazy match (*?), and check if the string that you're looking for is present in it:

// match any iframes
$pattern = '~<iframe.*?</iframe>~';
$content = preg_replace_callback($pattern, function($matches){

  if(strpos($matches[0], 'youtube') !== false) 
    return '<div class="video-container">' . $matches[0] . '</div>';

  return $matches[0];

}, $content);

Needless to say this will fail in many cases. If you want something reliable use an XML parser (see DomDocument::getElementsByTagName and DomElement::getAttribute.

You can also try to style your iframe with pseudo-selectors like :before or :after. That way you don't need a wrapper element (eg. iframe[src~=youtube]:after)

nice ass
  • 16,471
  • 7
  • 50
  • 89
  • Ah yes, I didnt think of using pseudo's to wrap the iframe. Ill give them a go. – user1385827 Feb 06 '13 at 21:48
  • the :before pseudo element won't work according to my tests and this post http://stackoverflow.com/a/13056674/1385827 – user1385827 Feb 06 '13 at 22:13
  • The php youve supplied above works. Im not sure why you say it will fail in many cases? Thanks again for your help. – user1385827 Feb 06 '13 at 22:23
  • Parsing HTML with regular expressions is generally not a good idea, because there will always be some string combination that your expression may not match. Indeed :before doesn't seem to work with iframes, so that leaves you with the other two options :) – nice ass Feb 06 '13 at 22:58
0

I think you just need to change the $pattern variable. Try with:

$pattern = '~<iframe.*src*=\'.*(http\:?)*\/\/*(www\.?)*youtube\..*</iframe>~';

Note: As @alex pointed, you are missing the protocol, so it should be http://youtube., //youtube. or http://www.youtube.

Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85