NaughtySquid
NaughtySquid

Reputation: 2097

Add http:// to a link if it doesn't have it

I have this very simple url bbcoder which i wish to adjust so if the linked does not contain http:// to add it in, how can i do this?

    $find = array(
    "/\[url\=(.+?)\](.+?)\[\/url\]/is",
    "/\[url\](.+?)\[\/url\]/is"
    );

    $replace = array(
    "<a href=\"$1\" target=\"_blank\">$2</a>",
    "<a href=\"$1\" target=\"_blank\">$1</a>"
    );

    $body = preg_replace($find, $replace, $body);

Upvotes: 0

Views: 390

Answers (3)

Martijn
Martijn

Reputation: 16103

// I've added the http:// in the regex, to make it optional, but not remember it,
// than always add it in the replace

$find = array(
    "/\[url\=(?:http://)(.+?)\](.+?)\[\/url\]/is",
    "/\[url\](.+?)\[\/url\]/is"
    );

    $replace = array(
    "<a href=\"http://$1\" target=\"_blank\">$2</a>",
    "<a href=\"http://$1\" target=\"_blank\">http://$1</a>"
    );

    $body = preg_replace($find, $replace, $body);

If you would use a callback function and preg_replace_callback(), you can use something like this: You can do that this way. It will always add 'http://', and than the string without 'http://'

$string = 'http://'. str_replace('http://', '', $string);

Upvotes: 3

Sswater Shi
Sswater Shi

Reputation: 189

You can use a (http://)? to match the http:// if exists, and ignore the group result in 'replace to' pattern and use your own http:// , like this:

$find = array(
"/\[url\=(http://)?(.+?)\](.+?)\[\/url\]/is",
"/\[url\](http://)?(.+?)\[\/url\]/is"
);

$replace = array(
"<a href=\"http://$2\" target=\"_blank\">$3</a>",
"<a href=\"http://$2\" target=\"_blank\">$2</a>"
);

$body = preg_replace($find, $replace, $body);

Upvotes: 4

Jazi
Jazi

Reputation: 6732

if(strpos($string, 'http://') === FALSE) {
    // add http:// to string
}

Upvotes: 4

Related Questions