0

i have a posting feature on my site that can embed links and youtube videos. the problem is, that the two clash together, and the youtube iframe ends up being a 404 page on my site. my codes for the youtube videos and links are below, but im not sure how to stop them from combining and ruining it.
by combining, i mean this http://www.youtube.com/watch?v=VhqiT2nWCVU turns to
<iframe src="http://www.youtube.com/watch?v=VhqiT2nWCVU">
which then turns into

<iframe src="<a href="http://www.youtube.com/watch?v=VhqiT2nWCVU"></a>">

sorry if i am unclear in any way. my codes are below.

function youtube($string)
{
  return preg_replace(
    '#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
    '<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4?rel=0" frameborder="0" allowfullscreen></iframe>',
    $string
  );
}

$posted = youtube($posted);

$rexProtocol = '(https?://)?';
$rexDomain   = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$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]+?)?';

// Solution 1:

function callback($match)
{
    // Prepend http:// if no protocol specified
    $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";

    return '<a href="' . $completeUrl . '">'
        . $match[2] . $match[3] . $match[4] . '</a>';
}


$posted = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
    'callback', $posted);
user2166538
  • 313
  • 1
  • 3
  • 18
  • See my answer to a nearly duplicate question: [How to find all Youtube video ids in a string using a regex?](http://stackoverflow.com/a/5831191/433790) Note that the regex in that answer skips over already-linked You-Tube URLs and will likely work quite well for your purposes. – ridgerunner Aug 26 '13 at 00:25

1 Answers1

1

A popular solution to this problem is to use placeholders. On your first pass you turn all YouTube links into a placeholder, for example:

{{youtube:VhqiT2nWCVU}}

After that you run your normal link converter. And at the end your run yet another regex to turn all your palceholders into youtube embeds.

Dragony
  • 1,712
  • 11
  • 20