3

文字列のURLをチェックし、<ahref>タグを追加してリンクを作成する小さなコードがあります。また、YouTubeリンクの文字列をチェックしてから、<a>タグにrel="youtube"を追加します。

YouTubeリンクにrelを追加するだけのコードを取得するにはどうすればよいですか?

どうすれば、任意のタイプの画像リンクに別の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="\0">\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="\0">\4</a>', $text ); 
          $type= 'youtube';
          }
else {
$type = 'none';
}
echo $text;
echo $linkstring, "<br />";
echo $type, "<br />";
4

2 に答える 2

2

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または単純な単一のリンクを構築できます。

URLのホスト名の検出:URLを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
)
于 2012-09-20T05:34:41.853 に答える
1

次のことを試してください。

//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">\0</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="\0">\0</a>';
$text = preg_replace($pattern, $replacement, $text);

後者は拡張子のある画像へのリンクしか検出できないことに注意してください。そのため、www.example.com?image=3のようなリンクは検出されません。

于 2012-09-20T05:53:40.520 に答える