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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.