我不久前写的这个函数将获取您输入的任何文本并设置电子邮件链接的 url 或嵌入 youtube 视频。它将删除 youtube url 的尾随字符。希望能帮助到你:
function MakeAutoLink($string)
{
/** Add http:// **/
$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string);
/** make all URLs links **/
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a rel=\"nofollow\" target=\"_blank\" href=\"$1\">$1</A>",$string);
/** make all emails hot links **/
$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A HREF=\"mailto:$1\">$1</A>",$string);
/** The Regular Expression filter **/
$youtube_video = "/v=(.+?)&/";
/** Check if there is a url in the text **/
$video = preg_match_all($youtube_video, $string, $match);
if ($video)
{
$links=$match[0];
for ($key=0;$key<$video;$key++)
{
$newstring = $string.'<br /><br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="320" height="185" src="http://www.youtube.com/embed/'.substr($links[$key], 2,11).'" frameborder="0" allowFullScreen></iframe><br />';
return $newstring;
}
}
return $string;
}
将此放在您的服务器上并导航到它进行测试:
视频.php
<?PHP
function MakeAutoLink($string)
{
/** Add http:// **/
$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string);
/** make all URLs links **/
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","$1",$string);
$youtube_video = "/v=(.+?)&/";
/** Check if there is a url in the text **/
$longurl = preg_match_all($youtube_video, $string, $match);
if ($longurl)
{
$links=$match[0];
for ($key=0;$key<$longurl;$key++)
{
$newstring = "http://www.youtube.com/watch?v=".substr($links[$key], 2,11);
return $newstring;
}
}
return $string;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?PHP
if(isset($_POST['video']))
{
echo MakeAutoLink($_POST['video']);
}
else
{
?>
Try these two links:<br>
http://www.youtube.com/watch?v=1rqQQkcB0MY<br><br>
http://www.youtube.com/watch?v=1rqQQkcB0MY&some more text<br>
<div align="center">
<form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
<label>video:</label>
<input type="text" title="Youtube video" name="video" size="60" value="" autocomplete="off" autofocus>
<br><br>
<input class="login" type="submit" name="login" value="Get Video">
</form>
</div>
<?PHP
}
?>
</body>
</html>
如果在使用“&”的视频 id 之后有其他选项,这将转换 url。如果您希望它在找到第一个空格后立即停止,请将/v=(.+?)&/替换为 /v=(.+?) /确保在 ) 和 / 之间留一个空格