我有一小段代码,可以检查字符串中的网址,并添加
如何获取代码以仅将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">