Maybe I misunderstood the OP, but wouldn't this (or something like it) be
easier and cleaner than that mess below??

$url = preg_replace("/(\...@\w+\.[a-za-z]{2,3})/i", "<a
href='mailto:$1'>$1</a>", $url);

$url = preg_replace("/\s(http:\/\/)?(\w*\.?\w*\.[a-zA-Z]{2,3}.*?\s)/i", " <a
href='http://$2' target='_blank'>$2</a>", $url);


> -----Original Message-----
> From: Nisse Engström [mailto:news.nospam.0ixbt...@luden.se] 
> Sent: Saturday, August 29, 2009 1:46 PM
> To: php-general@lists.php.net
> Subject: Re: [PHP] Converting URL's to hyperlinks.
> 
> On Fri, 28 Aug 2009 17:22:20 -0600, LinuxManMikeC wrote:
> 
> > <a href="<?php echo $url; ?>">click here</a>
> 
> *Groan*
> 
> Throw any random web site to an HTML validator
> and you're likely to see this kind of slop all
> over.
> 
> The correct solution is of course:
> 
>   $u = htmlspecialchars ($url);
>   echo "<a href=\"$u\">$u</a>";
> 
> 
> [A more elaborate way to flay this feline is
>  included below.]
> 
> 
> /Nisse
> 
> 
> /* Reworked from slightly different code.
>    Bugs may have been introduced.         */
> 
> <?php
> 
>   function url_to_links ($url)
>   {
>     if (preg_match ('@^([a-z]+://)(.*)@i', $url, $m)) {
>       $prfx = $m[1];
>       $path = $m[2];
>     } else {
>       return htmlspecialchars ($url);
>     }
> 
>     $url_sofar = $prfx;
>     $links = htmlspecialchars ($prfx);
> 
>     $segs = explode ('?', $path, 2);
>     if (isset ($segs[1]))
>       $query = $segs[1];
>     $segs = explode ('/', $segs[0]);
> 
>     for ($segn = 0; $segn < count ($segs); $segn++) {
>       $url_sofar .= $segs[$segn];
>       if (isset ($segs[$segn+1]))
>         $url_sofar .= '/';
> 
>       if ($segs[$segn] !== '') {
>         $links .= '<a href="' . htmlspecialchars ($url_sofar) . '">'
>                . htmlspecialchars ($segs[$segn]) . '</a>';
>       }
> 
>       if (isset ($segs[$segn+1]))
>         $links .= '/';
>     }
> 
>     if (isset ($query)) {
>       $url_sofar .= "?$query";
>       $links .= '?<a href="' . htmlspecialchars ($url_sofar)
>              .  '">' . htmlspecialchars ($query) . '</a>';
>     }
> 
>     return $links;
>   }
> 
>   $u = 'https://ebagwa.example/abd/def/ghi?s=t&u=v&w=x&y=z';
>   $u_h = htmlspecialchars ($u);
>   $links = url_to_links ($u);
> 
>   header ('Content-Type: text/html');
> 
>   echo <<<_
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
>   "http://www.w3.org/TR/html4/strict.dtd";>
> <title>url_to_links()</title>
> 
> <pre>
> $u_h
>   &#x2193;
> $links
> </pre>
> 
> _;
> 
> -- 
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
> 


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to