Zend - The PHP Company




Link Checkers

Add Code


OUCH! (opportunistic URL catching hack)  

Type: code fragment
Added by: karel007
Entered: 20/05/2002
Last modified: 06/12/2001
Rating: **** (3 votes)
Views: 5792
A regular expression to match a URL (http and https) in a text and replace it with the A tag. It also matches only www links (written without http://). And it doesn't include a possible character at the end of the link! MOSTLY CODED BY STAN!!! thanx! report any bugs an other features to me


<?php
//=============================================================================
//
// Function:    OUCH
//
// Input:       STRING $str  - a text or line
//
// Output:      STRING $str2 - a text or line with the links replaced with a 
//                             <A href tag
//
// Description: This function replaces a http, https or www in a text with a 
//              html A tag      
//
//=============================================================================
function OUCH($str)
{
  
// case insensitive regexp.
                       // -- protocol tag or www
  
$str2 preg_replace("!(((http(s?)://)|(www.))".   
               
// -- rest of the host, topdomain is 2-4 letters
               
"([-a-z0-9.]{2,}.[a-z]{2,4}".                                     
               
// -- port (optional)
               
"(:[0-9]+)?)".               
               
// -- path (optional)
               
"((/([^s]*[^s.,"'])?)?)". 
               // -- parameters (optional, but obligated to begin with a question mark)
               "((?([^s]*[^s.,"'
])?)?))!i",    
               // replace it with <a tag
               "
<a href="http\4://\5\6\8\9">\1</a>",
               
$str);

  return 
$str2;
}
?>


Usage Example


$str = "With text from a textarea, where the user can input some links like http://www.url.nl, sometime you want that the URL is set to a htm,l A tag instantly!n".
"Also a link without the http:// is a match like www.watchmouse.com.n".
"As you can see is the ending dot in the link not parsed and perfectly left alone!";

print OUCH($str);


Rate This Script





Search



This Category All Categories