Reputation: 673
I have created a blog in php. Users can write something and post it. If this includes a web address then a link automated is created using this :
<?php
//...code
$row['comment'] = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank"><font color="#69aa35">$1</font></a>', $row['comment']);
?>
Using this in posts, text posted successfuly and web address displayed in a link format inside text. Any idea how can I change this, so that if there is a link of youtube, then a youtube frame to be created. For example in facebook, when you post a youtube address, a youtube frame created and posted instead of a link.
Upvotes: 2
Views: 669
Reputation: 1420
I have improved my answer and tested this code:
<?php
// This is your comment string containing the youtube link
$string="Here is a link - https://www.youtube.com/watch?v=LJHFXenOPi4";
// This will remove all links from the input string
preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/?:@=_#&%~,+$]+/', $string, $matches);
foreach($matches as $url){
// Parse each url within the comment data
$input = parse_url($url);
if ($input['host'] == 'youtube.com' || $input['host'] == 'www.youtube.com' ) {
// If it is a youtube link, then parse the get variables
parse_str(parse_url($url, PHP_URL_QUERY), $variables);
// Echo out the iframe with the relevant video ID
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$variables['v'].'" frameborder="0" allowfullscreen></iframe>';
}
}
?>
I hope this is what you were looking for, it has worked for me on a few tests
Upvotes: 2
Reputation: 12834
You know the solution don't you? :) If the snippet contains youtube.com URL, then using the same pattern matching you can replace it with a youtube embed tag :)
Basically it will be something like this in pseudo-code.
If yes, then replace it with:
<iframe type="text/html"
width="640"
height="385"
src="<youtube URL>"
frameborder="0">
</iframe>
Upvotes: 1