Php разбирает ссылки / электронные письма - PullRequest
5 голосов
/ 24 июня 2009

Мне интересно, есть ли простой фрагмент, который преобразует ссылки любого вида:

http://www.cnn.com to <a href="http://www.cnn.com">http://www.cnn.com</a>
cnn.com to <a href="http://www.cnn.com">cnn.com</a>
www.cnn.com to <a href="http://www.cnn.com">www.cnn.com</a>
abc@def.com to  to <a href="mailto:mailto:abc@def.com">mailto:abc@def.com</a>

Я не хочу использовать какую-либо конкретную библиотеку PHP5.

Спасибо, что уделили время.

ОБНОВЛЕНИЕ Я обновил приведенный выше текст, чтобы преобразовать его в. Обратите внимание, что тег href и текст отличаются для случаев 2 и 3.

ОБНОВЛЕНИЕ2 Как это происходит в чате Gmail? Они довольно умные и работают только для реальных доменных имен. например a.ly работает, но a.cb не работает.

Ответы [ 4 ]

4 голосов
/ 24 июня 2009

да, http://www.gidforums.com/t-1816.html

<?php
/**
   NAME        : autolink()
   VERSION     : 1.0
   AUTHOR      : J de Silva
   DESCRIPTION : returns VOID; handles converting
                 URLs into clickable links off a string.
   TYPE        : functions
   ======================================*/

function autolink( &$text, $target='_blank', $nofollow=true )
{
  // grab anything that looks like a URL...
  $urls  =  _autolink_find_URLS( $text );
  if( !empty($urls) ) // i.e. there were some URLS found in the text
  {
    array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
    $text  =  strtr( $text, $urls );
  }
}

function _autolink_find_URLS( $text )
{
  // build the patterns
  $scheme         =       '(http:\/\/|https:\/\/)';
  $www            =       'www\.';
  $ip             =       '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
  $subdomain      =       '[-a-z0-9_]+\.';
  $name           =       '[a-z][-a-z0-9]+\.';
  $tld            =       '[a-z]+(\.[a-z]{2,2})?';
  $the_rest       =       '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';            
  $pattern        =       "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";

  $pattern        =       '/'.$pattern.'/is';
  $c              =       preg_match_all( $pattern, $text, $m );
  unset( $text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern );
  if( $c )
  {
    return( array_flip($m[0]) );
  }
  return( array() );
}

function _autolink_create_html_tags( &$value, $key, $other=null )
{
  $target = $nofollow = null;
  if( is_array($other) )
  {
    $target      =  ( $other['target']   ? " target=\"$other[target]\"" : null );
    // see: http://www.google.com/googleblog/2005/01/preventing-comment-spam.html
    $nofollow    =  ( $other['nofollow'] ? ' rel="nofollow"'            : null );     
  }
  $value = "<a href=\"$key\"$target$nofollow>$key</a>";
} 

?>
2 голосов
/ 08 сентября 2011

Попробуйте это. (по ссылкам не по электронной почте)

$newTweet = preg_replace('!http://([a-zA-Z0-9./-]+[a-zA-Z0-9/-])!i', '<a href="\\0" target="_blank">\\0</a>', $tweet->text);
0 голосов
/ 22 мая 2015

Я знаю, что на 5 лет позже, но мне нужно было подобное решение, и лучший ответ я получил от пользователя - erwan-dupeux-maire

Ответ

Я пишу эту функцию. Он заменяет все ссылки в строке. Ссылки могут быть в следующих форматах:

Второй аргумент является целью для ссылки («_blank», «_top» ... можно установить в false). Надеюсь, это поможет ...

public static function makeLinks($str, $target='_blank')
{
    if ($target)
    {
        $target = ' target="'.$target.'"';
    }
    else
    {
        $target = '';
    }
    // find and replace link
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
    // add "http://" if not set
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
    return $str;
}
0 голосов
/ 24 июня 2009

Вот фрагмент электронной почты:

$email = "abc@def.com";

$pos = strrpos($email, "@");
if (!$pos === false) {
    // This is an email address!
    $email .= "mailto:" . $email;
}

Что именно вы хотите сделать со ссылками? раздеть www или http? или добавить http://www к любой ссылке, если требуется?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...