Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Links, ereg?

Status
Not open for further replies.

GirishGupta

Programmer
May 28, 2001
30
GB
I want to search a string for each occurence of a link ( and then put <a> tags around it. This is what I have:

Code:
function MakeLink($text)
{
 $text = ereg_replace(&quot;([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])&quot;,  &quot;<a href=\&quot;\\1://\\2\\3\&quot; target=\&quot;_blank\&quot; target=\&quot;_new\&quot;>\\1://\\2\\3</a>&quot;, $text);
 $text = ereg_replace(&quot;(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))&quot;,  &quot;<a href=\&quot;mailto:\\1\&quot;>\\1</a>&quot;, $text);
    
 return $text;
}

echo MakeLink(&quot;This is an email address: email@email.com [URL unfurl="true"]http://www.microsoft.com/[/URL] fnsdf&quot;);

The only problem is that sometimes URLs are too long. So, I want to be able to change the URL that is displayed. For example: (semi-psuedo code)

Code:
$arrayvar = GetAllLinks($string); // An array

foreach($link as $arrayvar) // For each one of the links
{
  if (strlen($link)>=50) // if length of url is >= 50
  {
   $displaylink = substr($link, 0, 47).'...';  // take away last few chars and add '...'
  }
  else
  {
   $displaylink = $link; // length < 50
  }
 return &quot;<a href=\&quot;$link\&quot;>$displaylink</a>&quot;;
}

echo $the new string with the <a> tags and dots (...) if necessary;

Any ideas?

Girish Gupta
 
I've worked it out:

Code:
function MakeLinks($link)
{
 if (strlen($link)>50) 
 {        
  $linktext = substr($link,0,47).&quot;...&quot;; 
 } 
 else 
 {   
  $linktext = $link;
 }
return &quot;<a href=\&quot;$link\&quot; target=\&quot;_blank\&quot;>$linktext</a>&quot;;
}

 $var = preg_replace(&quot;/(?<!\S)((https?|ftp):\/\/\S+)/e&quot;, &quot;''.MakeLinks('\\1').''&quot;, $var);

echo $var;
Girish Gupta
girish@musicgoeson.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top