Reputation: 171
I have following text
"I made this video on my birthday. All of my friends are here in party. Click play to video the video
http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit "
What i want is to replace this above url to
"I made this video on my birthday. All of my friends are here in party. Click play to video the video
<iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe> "
I know we can get youtube video id from above url in following script
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $word, $matches);
$youtube_id = $matches[0];
But I dont know how to replace url
http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit
to
<iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe>
Please help Thanks
Upvotes: 3
Views: 1000
Reputation: 7739
Use preg_replace function (see PHP preg_replace() Documentation)
Edit :
Using preg_replace is as follows : you use parentheses () to wrap what you want to capture in the regex (first parameter) and then you use $n (n beeing the parenthese order in the regex) in the second parameter to get what you captured.
In your case you should have something like this :
$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit";
$replaced = preg_replace('#http://www\.youtube\.com/watch\?v=(\w+)[^\s]+#i','<iframe width="853" height="480" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>',$text);
For more advanced usage and examples see the documentation link I provided you before.
Hope this helps you more.
Edit 2 : The regex was wrong, I fixed it.
Upvotes: 2
Reputation: 369
You can use this sample code to achieve it, based on @Matt comment:
<?php
$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video
http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit ";
$rexProtocol = '(https?://)?';
$rexDomain = '(www\.youtube\.com)';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
function callback($match)
{
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
$videoId = array ();
preg_match ("|\?v=([a-zA-Z0-9]*)|", $match[5], $videoId);
return '<iframe src="http://www.youtube.com/embed/' . $videoId[1] . '" width="853" height="480"></iframe>';
}
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text));
?>
Upvotes: 0