[PHP] 텍스트 링크에 a 태그를 붙여서 실제 링크로 만들어 주는 함수

이 함수는 어디선가 긁은 거고, 당연히 완전하지 않다. 내가 만든 게 아니다.

//텍스트로 있는 링크에 a 태그를 붙여서 실제 링크로 만들어 주는 함수
function linkfy($s) {
  return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1">$1</a>', $s);
}

이런 것도 발견했다.

function convert_to_clickable($text){
  // Finds all http/https/ftp/ftps links that are not part of an existing html anchor
  if (preg_match_all('~\b(?<!href="|">)(?:ht|f)tps?://\S+(?:/|\b)~i', $text, $matches))
  {
    //checking for URLs
    foreach ($matches[0] as $match)
    {
      $clickable_link = "<a href=\" $match \"> $match </a>";
      $text = str_replace($match, $clickable_link, $text);

    }

  }

  //checking for emails
  if( preg_match_all('/[a-z0-9]+([\\+_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}/i',
      $text, $matches) ) {

    foreach( $matches[0] as $match ) {
      $clickable_link = "<a href=\"mailto:$match\"> $match </a>";
      $text = str_replace($match, $clickable_link, $text );
    }
  }

  return $text;
}

출처는 https://github.com/eyedol/linkfy 다.

👇 카테고리 글 목록

대표글

댓글 남기기