regex replace iframe/object by youtube video id - php

I have the html like below. Basically it has three videos some of them embed by iframe tag other object tag. I have the YouTube video id. So I want to replace the iframe/object tag with some text (Video can't be showed here ) by YouTube video id.
MY HTML
<p>Video 1</p>
<p><iframe width="604" height="453" src="http://www.youtube.com/embed/TOsGAxFcYls?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Video 2</p>
<p><iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Video 3</p>
<object width="560" height="315"><param name="movie" value="//www.youtube.com/v/-1jKtYuXkrQ?version=3&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="//www.youtube.com/v/-1jKtYuXkrQ?version=3&hl=en_US" type="application/x-shockwave-flash" width="560" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>
Now, I want to replace the replace the video 1 and 3. I have both video id's.
video 1 = TOsGAxFcYls
video 3 = -1jKtYuXkrQ
Now, I want to replace both iframe and object by particular text.
Expected output
<p>Video 1</p>
<p><strong>Video 1 has been removed video id (TOsGAxFcYls)</strong></p>
<p>Video 2</p>
<p><iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Video 3</p>
<strong>Video 3 has been removed video id (-1jKtYuXkrQ)</strong>
Note : I may add custom replacement text for each replacement of
video.
please help me out with regular expression to do the above job!

Here is a simple solution, just add the ID's and their replacement texts to the $video_ids array.
$html= ... // your html here
$video_ids = array
(
array("TOsGAxFcYls","First replacement text"),
array("Y-AYC3_DbpY","Second replacement text")
);
foreach ($video_ids as &$video_id) {
$patt = "/<object(.*)$video_id[0](.*)<\/object>/";
$html = preg_replace($patt, $video_id[1], $html);
$patt = "/<iframe.*?src\=".*?'.$video_id[0].'.*.<\/iframe>/i";
$html = preg_replace($patt, $video_id[1], $html);
}
echo $html; // here are your changed values

Here is a sample code that I believe has the effect your asking for:
<?php
$text = '<iframe width="604" height="340" src="http://www.youtube.com/embed/Y-AYC3_DbpY?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$matches = array();
$video_id = "Y-AYC3_DbpY";
preg_match('/<iframe.*?src\=".*?'.$video_id.'.*.<\/iframe>/i', $text, $matches);
if(!empty($matches)){
//replace iframe;
}
else{
//do something else
}
?>

Related

Find all ocurrences and replace one by one PHP

I'm replacing all ocurrences in a string to . And I'm doing:
1) I get video_id from youtube url.
preg_match('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);
2) I remove iframe with amp-youtube adding the url video id.
$string = preg_replace( '/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/',
'<amp-youtube data-videoid="'.$video_id[1].'" width="480" height="270" layout="responsive"></amp-youtube>', (str_replace("https://www.youtube.com/embed/","", $string)));
That works fine for just one ocurrence.
But If I have more than one iframe... Ok I can do
preg_match_all('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);
to get all video ids in the string.
But how can I loop to add each id to every amp-youtube data-videoid in a string??
Thanks!!
I wish you would have posted a minimal sample html string and your expected output, but I think I gather your meaning.
Don't use regex to parse html. Iterate while there is an existing iframe tag and replace it with your desired tag using the prepared substring from the iframe's src value.
Code: (Demo)
$html = <<<HTML
<div>
<p>
<iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw" width="640"></iframe>
</p>
<p>
<iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/abcdefghijk" width="640"></iframe>
</p>
</div>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
while ($iframe = $dom->getElementsByTagName('iframe')->item(0)) {
$amp = $dom->createElement('amp-youtube');
$amp->setAttribute('width', '480');
$amp->setAttribute('height', '270');
$amp->setAttribute('layout', 'responsive');
$amp->setAttribute('data-videoid', str_replace("https://www.youtube.com/embed/","", $iframe->getAttribute('src')));
$iframe->parentNode->replaceChild($amp, $iframe);
}
echo $dom->saveHTML();
Output:
<div>
<p>
<amp-youtube width="480" height="270" layout="responsive" data-videoid="sNEJOm4hSaw"></amp-youtube>
</p>
<p>
<amp-youtube width="480" height="270" layout="responsive" data-videoid="abcdefghijk"></amp-youtube>
</p>
</div>

HTML string append/replace in PHP

I have the following html string in my php code:
<iframe src="https://player.vimeo.com/video/123456789" width="604" height="340" frameborder="0" title="Ovarian Psycos - Teaser" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
I want to append parameters to the URL give in the src attribute. The result should look as follows:
<iframe src="https://player.vimeo.com/video/123456789/APPENDAGE" width="604" height="340" frameborder="0" title="Ovarian Psycos - Teaser" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
As you can see, in my example the string /APPENDAGE should be appended to the URL givein in the src attribute.
Usually I would do something like this with a string-replace method, however, in the given case this approach won't work. What would be an efficient approach to reach my goal?
If you don't mind using regex, there is a simple solution for this: (DEMO)
$str = '<iframe src="https://player.vimeo.com/video/123456789" width="604" height="340" frameborder="0" title="Ovarian Psycos - Teaser" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
';
$replaced = preg_replace('/(?<=src=")(.*?)(?=")/', '$1/APPENDAGE', $str);
var_dump($replaced);
Output:
string '<iframe src="https://player.vimeo.com/video/123456789/APPENDAGE" width="604" height="340" frameborder="0" title="Ovarian Psycos - Teaser" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
' (length=215)
This will simply match the url, insdie src attr and append /APPENDAGE to it, you can change it to whatever you want.
if you don't mind a large code
<?php
$str = '<iframe src="https://player.vimeo.com/video/123456789" width="604" height="340" frameborder="0" title="Ovarian Psycos - Teaser" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>';
$obj = simplexml_load_string($str);
//print_r($obj);
$obj['src'] = $obj['src'].'/APPENDAGE';
$s = $obj->asXML();
print(substr( $s, strpos($s, "\n")+1 ));
But this code will also work for rest of the attributes

Strip a section of an embed code with PHP

I'm trying to search JW Player embed codes like this one:
<iframe src="//content.jwplatform.com/players/ewQYJ6zA-F6KYzWLn.html" width="480" height="270" frameborder="0" scrolling="auto" allowfullscreen></iframe>
What I need to grab is the code right after players/ which in this embed would be just ewQYJ6zA.
Anyone have an idea how to go about this?
This will search for players/ followed by one or more letters and numbers.
<?php
$string = '<iframe src="//content.jwplatform.com/players/ewQYJ6zA-F6KYzWLn.html" width="480" height="270" frameborder="0" scrolling="auto" allowfullscreen></iframe>';
preg_match( '~/players/([[a-zA-Z\d]+)~', $string, $matches );
echo $matches[1];
?>
Output:
ewQYJ6zA
This regex in PHP should do the trick:
preg_match('/players\/(.+)-/im', $codetomatch, $codeyouwant);
Regex101

How to get all YouTube iframe from HTML using regex

I want to get all YouTube iframe using regex and want to add specific tag to each record found.
For example <youtube-frame></youtube-frame> to iframe begeing and end.
Needed output:
<youtube-frame><iframe width="560" height="315" src="https://www.youtube.com/embed/vakfMRyjulw" frameborder="0" allowfullscreen></iframe></youtube-frame>
<youtube-frame><iframe width="560" height="315" src="https://www.youtube.com/embed/aDGWMlKPKDs" frameborder="0" allowfullscreen></iframe></youtube-frame>
My Code
$embed = '
<iframe width="560" height="315" src="https://www.youtube.com/embed/vakfMRyjulw" frameborder="0" allowfullscreen></iframe>
<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folderp2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/aDGWMlKPKDs" frameborder="0" allowfullscreen></iframe>
<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folder=2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe>
<iframe width="600" height="350" src="https://tune.pk/player/embed_player.php?vid=6508414&folder=2016/05/04/&width=600&height=350&autoplay=no" frameborder="0" allowfullscreen scrolling="no"></iframe>
';
What I have tried?
$pattern = '/<iframe\.*src=\"//youtube"\.*/';
$iframeSrc = preg_match($pattern, $embed, $matches);
var_dump($iframeSrc);
Try this:
$iframeSrc = preg_replace('/<iframe[^>]*src\s*=\s*"?https?:\/\/[^\s"\/]*youtube.com(?:\/[^\s"]*)?"?[^>]*>.*?<\/iframe>/i', '<youtube-frame>$0</youtube-frame>', $embed);
This uses preg_replace and a global regex to replace all YouTube IFrame tags (including their closing tags) with <youtube-frame>$0</youtube-frame> where $0 is the original string.
The regex could theoretically be simplified if you are totally sure about the format of your input, but I designed it to be robust enough to cope with other syntaxes such as src=http://example.com or src = "http://example.com" etc. which are accepted by browsers nowadays, and it only matches sources on *.youtube.com domains and not something like myyoutubesite.com.

PHP - How to select random tag in the string

For example, I have this string containing some number of iframe tags (but there can be also some text or links, so the point is to select only iframe tags):
<p><iframe frameborder="0" height="180" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaphchapeau-rouge-2022014%2F&embed_type=widget_standard&embed_uuid=9ff7c333-5c68-40d6-b9c7-b475c6a8d297&hide_tracklist=1&replace=0&hide_cover=1" width="600" ></iframe></p>
<p><iframe frameborder="0" height="180" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fx-tract-podcast-night-30-skaph%2F&embed_type=widget_standard&embed_uuid=7186f43a-4bc7-431d-8041-f51366355c44&hide_tracklist=1&replace=0&hide_cover=1" width="600" ></iframe></p>
<p><iframe frameborder="0" height="180" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaphclick-clack-07122013-experiment-liberec%2F&embed_type=widget_standard&embed_uuid=7f2202e6-fd70-45ac-ac1e-6c9dca0ad725&hide_tracklist=1&replace=0&hide_cover=1" width="600" ></iframe></p>
<p><iframe frameborder="0" height="180" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2FTFSpodcast%2Ftechno-for-soul-podcast-11-mixed-by-skaph%2F&embed_type=widget_standard&embed_uuid=e3f68ffd-488d-4d78-b369-a46c785f59a5&hide_tracklist=1&replace=0&hide_cover=1" width="600" ></iframe></p>
<p><iframe frameborder="0" height="180" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaphtechno-je-v%C5%A1echno-5%2F&embed_type=widget_standard&embed_uuid=2c80035e-27e8-4321-b07d-395e6777b98c&hide_tracklist=1&replace=0&hide_cover=1" width="600" ></iframe></p>
<p><iframe frameborder="0" height="132" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaphtechno-je-v%25C5%25A1echno-vol-2-liberec-experiment-18052013%2F&embed_uuid=f81d24a4-c2f8-4bc5-a10f-7f3fb2243392&stylecolor=&embed_type=widget_standard" width="480"></iframe></p>
<p><iframe frameborder="0" height="132" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaphexperiment-18012013%2F&embed_uuid=e63685e9-901c-4d71-a1c5-69d0afb130d6&stylecolor=&embed_type=widget_standard" width="480"></iframe></p>
<p><iframe frameborder="0" height="132" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaph-renaissance-winter-mix-2012%2F&embed_uuid=5a7e4685-cf6a-4f84-ba1c-13251d5b7f59&stylecolor=&embed_type=widget_standard" width="480"></iframe></p>
<p><iframe frameborder="0" height="132" src="http://www.mixcloud.com/widget/iframe/?feed=http%3A%2F%2Fwww.mixcloud.com%2Fskaph%2Fskaph-mini-technik%2F&embed_uuid=7818bedc-94d0-46b1-8193-4cafcf65ffb5&stylecolor=&embed_type=widget_standard" width="480"></iframe></p>
I need to select random iframe tag string from this and I need both opening and closing tag to be included. I suppose I should use something like explode and then use array_rand() function, but there is no divider. Other option that came to my mind is regex, but understanding of that still escapes me.
Regular expressions are not suitable for parsing HTML. Use a DOM parser instead -- here's a solution using PHP's native DOMDocument class:
$dom = new DOMDocument;
$dom->loadHTML($html);
$iframes = $dom->getElementsByTagName('iframe');
$index = mt_rand(0, $iframes->length);
$random_tag = $iframes->item($index);
In the above code, first a random index between 0 and the total number of tags ($iframes->length) is chosen with mt_rand(), and then the item() method is used to specifically access that tag. Once you have the tag, you can do any further processing. In the demo, I've shown you how to extract the src attribute just to show it's random.
Online demo

Categories