以下のコードは、URL の文字列からのテキストをチェックし、クリック可能なリンクに変換しています。
画像へのリンクがある場合、 < a> タグに rel="image" を追加するように取得しようとしています。YouTube の動画がある場合は、< a> タグに rel="youtube" を追加します。
文字列にリンクが 1 つしかない場合は正常に機能します。複数ある場合、すべてのリンクは最後のリンクの rel を取得します。
$text = "http://site.com a site www.anothersite.com/ http://imgur.com/image.png http://youtu.be/UyxqmghxS6M here is another site";
$linkstring = preg_replace('/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i', '<a rel="iframe" href="\0">\0</a>', $text );
if(preg_match('/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i', $linkstring, $vresult)) {
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i";
$replacement = '<a rel="youtube" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'youtube';
} elseif(preg_match('/(http(s?):)?|([\/|.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)/i', $linkstring, $vresult)) {
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i";
$replacement = '<a rel="image" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'image';
} else {
$type = 'none';
}
echo $text, "<br />";
echo $text2, "<br />";
echo $linkstring, "<br />";
echo $type, "<br />";
YouTube または画像リンクと同じ正規表現に一致するように $pattern を変更しようとしましたが、URL の後にテキスト全体のリンクが作成されてしまいます。
例:
$text = "http://site.com a site www.anothersite.com/ http://imgur.com/image.png http://youtu.be/UyxqmghxS6M here is another site";
$linkstring = preg_replace('/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i', '<a rel="iframe" href="\0">\0</a>', $text );
if(preg_match('/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i', $linkstring, $vresult)) {
$pattern = "/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i";
$replacement = '<a rel="youtube" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'youtube';
} else {
$type = 'none';
}