Help - Search - Members - Calendar
Full Version: Text to Link using Regular Expressions
Weborum Webmaster Forum > Web Page Design > PHP
toad78
I've been advised to use regular expressions when search a string of text in order to create a link from it.

My situation: I have text coming from a database table and within that db table is a paragraph of text that includes a web address.

I was given this to use, but don't know where exactly to put it and if this will actually work:

PHP Code:
CODE
<?php
function hyperlink($text) {
    // match protocol://address/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*
            [a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i",
            " <a href=\"$1\" target=\"_blank\">$1</a>$2", $text);
    // match www.something.domain/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/\s(www\.[a-z][a-z0-9\_\.\-]*
            [a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i",
            " <a href=\"http://$1\" target=\"_blank\">$1</a>$2", $text);
    // match name@address
    $text = preg_replace("/\s([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*
            \@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})([\s|\.|\,])/i",
            " <a href=\"mailto://$1\">$1</a>$2", $text);
    return $text;
}
?>



My HTML:
Code:
CODE
<p><?php echo nl2br($row_recent_event['description']); ?></p>


I would appreciate any suggestions!
toad78
Waleed
Hi toad78, welcome to Weborum!

That function looks like it should work, though I can't test it right now.

To make it work, you need to run the text from the database through the function.
CODE
$linked = hyperlink($row_recent_event['description']);

<p><?php echo nl2br($linked); ?></p>


The above code takes the result from the database and runs it through the function (that searches for and formats links), then puts it in a new variable named linked. Then, the text in linked is echo'd inside the <p> tags.

Of course, you need to put in the function code somewhere in the page before you use the above code.

Hope that explains it!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.