Jump to content

preg_replace for urls


jdeutsch

Recommended Posts

I recently found the following code on php.net listed under preg_replace.  It does exactly what I'm trying to accomplish, however, it does the capture the TLD of the domain in question.

 

CODE (extra spaces in regex added to keep code from running too long on the page):

<?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;
}
?>

 

For example, when attempting to extract http://www.google.com from a string, it gets "http://www.google" and nothing else.

 

I am not very familiar with regular expressions, so if someone could tell me how to tweak the expressions to include the TLD (and any info after the domain - get variables, etc.), it would be greatly appreciated.

Link to comment
https://forums.phpfreaks.com/topic/83924-preg_replace-for-urls/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.