自動リンク


/ Published in: PHP
Save to your folder(s)

文字列中のURLとメールアドレスをリンクに変換する


Copy this code and paste it in your HTML
  1. /**
  2.  * URLをリンクに変換する
  3.  * @param string $content 変換する文字列
  4.  * @return stiring 変換後の文字列
  5.  */
  6. function cnvUrlToLink($content){
  7. $res="";
  8. $s=preg_split("/\n/",$content);
  9. foreach($s as $line){
  10. $pat=array(
  11. "/(https?:\/\/[\w\.\~\-\/\?\&\+\=\:\;\@\%\,]+)/",
  12. "/([\w\.\-_]+@[\w\-_]{2,}\.[\w\.\-_]{2,})/",
  13. );
  14. $rep=array(
  15. "<a href=\"\${1}\">\${1}</a>",
  16. "<a href=\"mailto:\${1}\">\${1}</a>",
  17. );
  18. $res.=preg_replace($pat,$rep,$line);
  19. }
  20. return($res);
  21. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.