2012-09-21 47 views
0

什么是最简单的方法来执行以下操作?最简单的方法来自动链接文本并添加链接

随机输入:

check out my new video here http://www.youtube.com/watch?v=123abc 
or here http://youtu.be/123abc 
here is my new wallpaper http://somepage.com/fRDTk.jpg 
and my new homepage http://google.com 

输出:

check out my new video here 
<a class="youtube" href="http://www.youtube.com/watch?v=123abc"> 
http://www.youtube.com/watch?v=123abc</a> 
or here 
<a class="youtube" href="http://youtu.be/123abc"> 
http://youtu.be/123abc</a> 
here is my new wallpaper 
<a class="image" href="http://somepage.com/fRDTk.jpg"> 
http://somepage.com/fRDTk.jpg</a> 
and my new homepage 
<a class="iframe" href="http://google.com"> 
http://google.com</a> 

什么是自动链接并添加取决于链路上的特定类的最简单的方法? (图片,youtube,其他)

我把它放在一起,但它的失败悲惨。

<?php 
foreach ($imgur->captions->item as $comment) { 
$co = $comment->caption; 
$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="fancybox fancybox.iframe" href="\0">\0</a>', $co); 
if(preg_match('/^http:\/\/(?:www\.)?(?:youtube.com|youtu.be)\/(?:watch\?(?=.*v=([\w\-]+))(?:\S+)?|([\w\-]+))$/i', $co, $vresult)) { 
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i"; 
$replacement = '<a class="fancybox-media" href="\0">\0</a>'; 
$text = preg_replace($pattern, $replacement, $co); 
      $type= 'youtube'; 
      } 
elseif(preg_match('/(http(s?):)?([\/.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)/i', $co, $vresult)) { 
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i"; 
$replacement = '<a class="fancybox" href="\0">\0</a>'; 
$text = preg_replace($pattern, $replacement, $co); 
      $type= 'image'; 
      } 
else { 
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i"; 
$replacement = '<a class="fancybox fancybox.iframe" href="\0">\0</a>'; 
$text = preg_replace($pattern, $replacement, $co); 
$type = 'none'; 
} 
echo "<div class=\"icomment\"> 
<p class=\"icomment\">&ldquo;",$text,"&rdquo; &#45;",$comment->author,"</p> 
</div>"; 
} 
?> 

我一直在搞这么多,只是想要报废它。希望有一个更简单的方法来做到这一点。

回答

0
$patterns = array(
    array('pattern'=>'/mypattern/','replaceWith'=>'myreplacement\0','addClass'=>'myclass'), 
    array('pattern'=>'/mypattern/','replaceWith'=>'myreplacement\0','addClass'=>'myclass'), 
); 

foreach($patterns as $pattern) { 
    // .... do your thing here... once... for every possibility described in array above. 
} 
+0

任何更简单的自动链接方法? – user1568736