-3

Possible Duplicate:
parse youtube video id using preg_match

$message = "this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id";

$message = preg_replace('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', '\\1', $message);

print $message;

the above prints...

this is an youtube video http://www.w6yF_UV1n1o&feature=fvst i want only the id

what i want is:

this is an youtube video w6yF_UV1n1o i want only the id

thanks in advance :)

Community
  • 1
  • 1
D.Snap
  • 1,704
  • 1
  • 22
  • 15
  • i didn't wanted to parse only a URL i wanted to parse a whole message, this is for a vBulletin board, so the users cas only paste a link and the youtube video will magically appears :) – D.Snap Oct 21 '12 at 23:55

1 Answers1

1

First you would match a valid URL, then extract a valid YouTube ID from that URL, then replace the original URL found with the matching ID (if a valid ID was found):

<?php

$message = "
    this is a youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id
    this is not a youtube video http://google.com do nothing
    this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id
";

preg_match_all('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#', $message, $matches);

if (isset($matches[0]))
{
    foreach ($matches[0] AS $url)
    {
        if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches))
            $message = str_replace($url, $matches[1], $message);
    }
}

echo $message;

Source: http://daringfireball.net/2009/11/liberal_regex_for_matching_urls & https://stackoverflow.com/a/6382259/1748964

Community
  • 1
  • 1
noetix
  • 4,773
  • 3
  • 26
  • 47
  • *"Try this:"* is a [subpar answer decoration](http://stuck.include-once.org/#help10). Instead please add a slim explanation of *what* your code does, *why* you'd recommend it, or *how* you came to the conclusion. -- More importantly, attribution please if you found the regex elsewhere. Seems based on this one http://daringfireball.net/2009/11/liberal_regex_for_matching_urls – mario Oct 21 '12 at 23:47
  • well that didn't worked, what if there is a message with two urls ? :P thanks anyway – D.Snap Oct 22 '12 at 00:17
  • Updated with a multiple URL example. – noetix Oct 22 '12 at 00:22
  • this will be for a vbulletin board, so users can input a youtube link on their message and the youtube video will appear automagically, is this CPU intensive ?... thanks !!! – D.Snap Oct 22 '12 at 00:35