Using preg_match and PHP regex get youtube embed vars

Post Reply
darknkreepy3#
Site Admin
Posts: 253
Joined: Tue Oct 27, 2009 9:33 pm

Using preg_match and PHP regex get youtube embed vars

Post by darknkreepy3# »

I wanted to write a program for a client that took an embed code and broke it up for a mysql database table. Since some pages will not always be a certain Width and Height, I wanted to extract the original data and then use it's size as a proportional reference, etc, and strip the youtube link video signature. Here is how to break things up in PHP and play with it from there.

test_youtube.php

Code: Select all

<form name="youtube" method="POST" action="extractor.php">
	<h3>copy and paste your youtube SHARE > EMBED (iframe) text here</h3>
	<textarea name="youtubeEmbed" cols="80" rows="1"></textarea>
	<input type="submit" value="test">
</form>
extractor.php

Code: Select all

<?php
	/*
	youtube variable extractor v1.0 by Kristoffe Brodeur. ©2013 All Rights Reserved.
	07-21-2013
	*/
	$data='<iframe width="560" height="315" src="//www.youtube.com/embed/YvIMajtdAtA" frameborder="0" allowfullscreen></iframe>';
	//
	if(isset($_POST['youtubeEmbed']))
		{
		$data=$_POST['youtubeEmbed'];
		}
	
	$pattern='/<iframe (.*)></s';//find everything after <iframe(space)----and---->< which is the first end tag of the iframe 
	preg_match($pattern,$data,$matches);
	$len=count($matches);//[0] holds the string [1~] and on holds the result(s)
	$mStr="";
	//
	for($a=0;$a<$len;$a++)
		{
		$mStr.="$a|".$matches[$a]."\n";
		}
		
	echo 
		"
		<textarea>$pattern</textarea>
		<h3>$len</h3>
		<textarea cols='120' rows'5'>".$mStr."</textarea>
		<hr />
		";
	
	echo "<table border='1' cellpadding='8px'>";
	
	$varTempArr=explode(" ",$matches[1]);
	$lenV=count($varTempArr);
	$vidArr=Array();
	//
	for($v=0;$v<$lenV;$v++)
		{
		$tmpArr=explode("=",$varTempArr[$v]);
		$patternQ='/"(.*)"/s';//find everything within the first and next quote
		preg_match($patternQ,$tmpArr[1],$resultNoQuotes);
		$strNoQuotes="-empty-";
		$lenQ=count($resultNoQuotes);
		//
		if($lenQ>0)
			{
			$strNoQuotes=$resultNoQuotes[1];
			}
		$vidArr[$tmpArr[0]]=$tmpArr[1];//evaluate the node name and enter it as a string in php {*}
		echo "<tr><td>".$tmpArr[0]."</td><td>".$strNoQuotes."</td></tr>";
		}
	echo "</table>";
	echo "<h3>testing vidArr for src | ".$vidArr['src']."</h3>";
	$patternS='/embed\/(.*)"/s';
	preg_match($patternS,$vidArr['src'],$resultSrc);
	echo "<h3>[".$resultSrc[1]."]</h3>";
?>
Post Reply