-3

I need a php regex that will do the following with my original string

<div>The quick jumped over <p>[video=xdf890sfadf]</p> the white fence.</div>

to

<div>The quick jumped over <p><iframe src="http://www.youtube.com/embed/xdf890sfadf?rel=0&amp;vq=hd720" height="365" width="650" allowfullscreen="" frameborder="0"></iframe></p> the white fence.</div>

So what I need do to is pull the video ID out of the any give string of html.

I want to use the preg_replace() function for this, but I'm confused about the proper regex to use with it. Please help.

liquidgraph
  • 103
  • 9
  • For your particular format: `$hit = preg_match("~youtube\.com/embed/\K[^?#\s]+~",$string,$m); if($hit) { $id = $m[0]; }` However, YouTube IDs come in a variety of formats: see [this comprehensive answer](http://stackoverflow.com/q/5830387/) – zx81 Jun 17 '14 at 00:31

1 Answers1

2

A simple search here on SO and should be no problem. Just get it using preg_match(). Consider this example:

$original_string = '<div>The quick jumped over <p>[video=xdf890sfadf]</p> the white fence.</div>';
preg_match('/\[video=([^\]]+)\]/', $original_string, $matches);
if(!empty($matches)) {
    $value = $matches[1];
    $video = $matches[0];
    $new_string = '<div>The quick jumped over <p><iframe src="http://www.youtube.com/embed/'.$value.'?rel=0&amp;vq=hd720" height="365" width="650" allowfullscreen="" frameborder="0"></iframe></p> the white fence.</div>';
    echo $new_string;
}

Note: credit goes to https://stackoverflow.com/a/8935740/1978142

Sample Output

Community
  • 1
  • 1
user1978142
  • 7,946
  • 3
  • 17
  • 20
  • I need to further clarify: the original string can have square brackets in other areas which must remain unaffected. I need to really match "[video= ]" – liquidgraph Jun 17 '14 at 00:40
  • @liquidgraph if you want to literaly match that sequence, check the edit – user1978142 Jun 17 '14 at 00:55