检查 YouTube 链接或图片的字符串



我有一小段代码,可以检查字符串中的网址,并添加标签来创建链接。我还让它检查 youtube 链接的字符串,然后将 rel="youtube" 添加到 标签中。

如何获取代码以仅将rel添加到YouTube链接?

如何让它为任何类型的图像链接添加不同的rel?

$text = "http://site.com a site www.anothersite.com/ http://www.youtube.com/watch?v=UyxqmghxS6M here is another site";
$linkstring = preg_replace( '/(http|ftp)+(s)?:(//)((w|.)+)(/)?(S+)?/i', '<a href="">4</a>', $text ); 
if(preg_match('/http://www.youtube.com/watch?v=[^&]+/', $linkstring, $vresult)) {
    $linkstring = preg_replace( '/(http|ftp)+(s)?:(//)((w|.)+)(/)?(S+)?/i', '<a rel="youtube" href="">4</a>', $text ); 
          $type= 'youtube';
          }
else {
$type = 'none';
}
echo $text;
echo $linkstring, "<br />";
echo $type, "<br />";

尝试 http://simplehtmldom.sourceforge.net/。

代码

<?php
include('simple_html_dom.php');
$html = str_get_html('<a href="http://www.youtube.com/watch?v=UyxqmghxS6M">Link</a>');
$html->find('a', 0)->rel = 'youtube';
echo $html;

输出

[username@localhost dom]$ php dom.php
<a href="http://www.youtube.com/watch?v=UyxqmghxS6M" rel="youtube">Link</a>

您可以使用此库构建整个页面 DOM 或简单的单个链接。

正在检测网址的主机名:将网址传递给parse_url。 parse_url返回 URL 部分的数组。

代码

print_r(parse_url('http://www.youtube.com/watch?v=UyxqmghxS6M'));

输出

Array
(
    [scheme] => http
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=UyxqmghxS6M
)

尝试以下操作:

//text
$text = "http://site.com/bounty.png a site www.anothersite.com/ http://www.youtube.com/watch?v=UyxqmghxS6M&featured=true here is another site";
//Youtube links
$pattern = "/(http://){0,1}(www.){0,1}youtube.com/watch?v=([a-z0-9-_|]{11})[^s]*/i";
$replacement = '<a rel="youtube" href="http://www.youtube.com/watch?v=3"></a>';
$text = preg_replace($pattern, $replacement, $text);
//image links
$pattern = "/(http://){0,1}(www.){0,1}[^/]+/[^s]+.(png|jpg|jpeg|bmp|gif)[^s]*/i";
$replacement = '<a rel="image" href=""></a>';
$text = preg_replace($pattern, $replacement, $text);

请注意,后者只能检测指向具有扩展名的图像的链接。因此,不会检测到像www.example.com?image=3这样的链接。

最新更新