[thelist] [php] preg_replace text links?

Kae Verens kverens at contactjuggling.org
Mon Nov 3 06:01:11 CST 2003


kris burford wrote:

> hi,
>
> i'm trying to get my head around some regex in php which i've lifted 
> (with only minor understanding) from "mastering regex expressions".
>
> what i'm trying to do is scan user submitted text (parsed through 
> htmlspecialchars) pick out any links and link 'em up.
>
> the starting pattern (from the book) is at 
> http://www.midtempo.net/regex.html but it just gives me "Warning: 
> Delimiter must not be alphanumeric or backslash". i've tried countless 
> additions of backslashes and googled for help, all to no avail...
>
> has anyone done this before? if so, where am i going wrong?


I use something like this (excerpt):

$a=preg_replace("/(http:\/\/|www|[a-zA-Z0-9-]+\.|[a-zA-Z0-9\.-]+@)(([a-zA-Z0-9-][a-zA-Z0-9-]+\.)+[a-zA-Z0-9-\.\/\_\?\%\#\&\=\;\~\!\(\)]+)/","<a 
href=\"http://\\1\\2\">\\1\\2</a>",$a);

that extracts most links and creates HTML links. I use the following to 
allow more control:

 $a=preg_replace("/\[<a([^>]*>)[^<]*<\/a>\|(.*?)\]/" , "<a\\1\\2</a>" ,$a);

lets the user write a link as [http://contactjuggling.org/|contact 
juggling], and that then links the words "contact juggling" to 
http://contactjuggling.org/

Kae



More information about the thelist mailing list