Regex PHP - Auto-detect YouTube, image and quot;regularquot; links(Regex PHP - 自动检测 YouTube、图像和“常规链接)
问题描述
我希望在我的聊天应用程序中,可以点击指向网站的链接,并自动嵌入指向 YouTube 和图像的链接.
I want to make it so that in my chat-application, links to websites can be clickable and links to YouTube and images automatically gets embedded.
我已经为我的 WebIRC 客户端使用 Java 编写了这段代码,但现在我正在尝试使用 PHP 和 JavaScript 编写它.
I've made this code in Java for my WebIRC client but now I'm trying to make it in PHP and JavaScript.
我还不熟悉 PHP,所以我不太了解在那里使用正则表达式.我想知道是否有好心人能帮我解决这个问题...
I'm not familiar with PHP yet so I don't know that much about using regex there. I wonder if some kind soul could help me with this...
对于 YouTube 的东西,我尝试过但没有成功:
For the YouTube-thingy I tried this without success:
if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v/)[^&
]+|(?<=v=)[^&
]+|(?<=youtu.be/)[^&
]+#", $message, $m)) {
$video_id = $m[1];
$message = preg_replace("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v/)[^&
]+|(?<=v=)[^&
]+|(?<=youtu.be/)[^&
]+#","<iframe class='embedded-video' src='http://www.youtube.com/embed/" . $video_id . "' allowfullscreen></iframe>",$message);
}
推荐答案
这是我想出的解决方案:
Here is a solution I came up with:
$str = 'This is an image: google.ca/images/srpr/logo3w.png
YouTube: http://www.youtube.com/watch?v=V2b8ilapFrI&feature=related
Stackoverflow: http://stackoverflow.com/';
$str = preg_replace_callback('#(?:https?://S+)|(?:www.S+)|(?:S+.S+)#', function($arr)
{
if(strpos($arr[0], 'http://') !== 0)
{
$arr[0] = 'http://' . $arr[0];
}
$url = parse_url($arr[0]);
// images
if(preg_match('#.(png|jpg|gif)$#', $url['path']))
{
return '<img src="'. $arr[0] . '" />';
}
// youtube
if(in_array($url['host'], array('www.youtube.com', 'youtube.com'))
&& $url['path'] == '/watch'
&& isset($url['query']))
{
parse_str($url['query'], $query);
return sprintf('<iframe class="embedded-video" src="http://www.youtube.com/embed/%s" allowfullscreen></iframe>', $query['v']);
}
//links
return sprintf('<a href="%1$s">%1$s</a>', $arr[0]);
}, $str);
如果您需要我为您澄清任何事情,请告诉我.
Let me know if you need me to clarify anything for you.
这篇关于Regex PHP - 自动检测 YouTube、图像和“常规"链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Regex PHP - 自动检测 YouTube、图像和“常规"链接
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
