Reputation: 9
Okay everyone, I have found multiple ways of doing this and I have even got it to work but my issue is this, the preg_replace from my understanding should replace everything that matches the pattern but it appears to only run once.
Here is what I need, I have a site that is running a feature that let's users post whatever they want on their profile, we want to let them also post youtube links and have these links turn into embeds. The problem arises when they post more then one video, it will only embed one of the videos and worse it removes the text.
$test = "This is a great lecture: http://www.youtube.com/watch?v=Ps8jOj7diA0 This is another great lecture http://www.youtube.com/watch?v=k6U-i4gXkLM What are your opinions on the two?"
$patterns[] = '|http://www\.youtube\.com/watch\?.*\bv=([^ ]+)|';
$replacements[] = ' <br /><iframe width="420" height="315" src=http://www.youtube.com/embed/$1 frameborder="0" allowfullscreen></iframe><br />';
$patterns[] = '|&feature=related|';
$replacements[] = '';
$test = preg_replace($patterns, $replacements, $test);
echo $test;
Output:
"This is a great lecture:
<iframe width="420" height="315" src=http://www.youtube.com/embed/k6U-i4gXkLM frameborder="0" allowfullscreen></iframe>
What are your opinions on the two?"
So you see... It cuts out everything between the first and second video and only embeds the second video. I need a solution that will let me remove the extra stuff produced by youtube links and also keep all the text of the messages that users post. Any idea's guys? Thanks.
Upvotes: 0
Views: 1397
Reputation: 443
There are two problems with Jack's code: - it does not properly catch links that are at the end of a line (\n character) - it does not remove optional additional parameters (eg. &list=...)
Here is the complete code:
$test = "This is a great lecture: http://www.youtube.com/watch?v=Ps8jOj7diA0&list=PL33AFE53E080251DF This is another great lecture http://www.youtube.com/watch?v=k6U-i4gXkLM What are your opinions on the two?"
$patterns = array('|http://www\.youtube\.com/watch\?.*?\bv=([^&]+).+?\s|i');
$replacements = array(' <br /><iframe width="400" height="300" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe><br />');
$test= preg_replace($patterns, $replacements, $test);
Upvotes: 0
Reputation: 5768
Make it non-greedy.
http://www\.youtube\.com/watch\?.*?\bv=([^ ]+)
Note the extra ?
here ?.*?
from http://www\.youtube\.com/watch\?.*\bv=([^ ]+)
Upvotes: 2