2013-08-25 22 views
0

我有我的网站上可以嵌入链接和YouTube视频的发布功能。问题是,这两个冲突在一起,而YouTube的iframe最终成为我网站上的404页面。我的YouTube视频和链接代码如下,但我不知道如何阻止他们合并和毁坏它。
结合,我的意思是这http://www.youtube.com/watch?v=VhqiT2nWCVU变成
<iframe src="http://www.youtube.com/watch?v=VhqiT2nWCVU">
然后变成PHP的YouTube和链接正则表达式组合,反过来渲染无用

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

对不起,如果我以任何方式还不清楚。我的代码如下。

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:;[email protected]_\':;!a-zA-Z\x7f-\xff]*?)?'; 
$rexQuery = '(\?[!$-/0-9:;[email protected]_\':;!a-zA-Z\x7f-\xff]+?)?'; 
$rexFragment = '(#[!$-/0-9:;[email protected]_\':;!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); 
+0

看到我的答案几乎重复的问题:[如何使用正则表达式查找字符串中的所有Youtube视频ID](http://stackoverflow.com/a/5831191/433790)请注意,该答案中的正则表达式跳过已经链接的You-Tube网址,并可能适用于您的目的。 – ridgerunner

回答

1

这个问题的一个流行解决方案是使用占位符。在你第一遍你把所有的YouTube链接到一个占位符,例如:

{{youtube:VhqiT2nWCVU}} 

后,您运行正常的链接转换器。最后再运行另一个正则表达式,将所有的参与者转化为youtube嵌入。

+0

你可以解释一下这个例子吗? – user2166538

+1

http://rextester.com/OMOCIS38257要查看它在底部按“运行它” – Dragony

+0

谢谢@dragony如果能运行,我会接受你的回答 – user2166538