martenolofsson
martenolofsson

Reputation: 531

Replace all occurences in string except the ones starting with "http" or "https" with php

I'm trying to write a function in php where I want to replace all occurences of "www." with "http://www.".

$text = preg_replace("www\.", "http://www.", $data);

I've tried using this code but I do not want the string "http://www." to be turned into "http://http://www.".

Any suggestions?

Upvotes: 1

Views: 145

Answers (5)

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

Add the ^ anchor to you regex:

$text = preg_replace("/^www\./", "http://www.", $data);
                       ^ -- this one

NB: mind the regex delimiters (/.../) in the pattern parameter.

This start of line anchorhelps to ensure the www. string to be replaced is at the beginning of the $data string. It will prevent any undesired substitutions in the middle of a string like this: redirector.com/?www.stackoverflow.com

Upvotes: 3

Devraj Gupta
Devraj Gupta

Reputation: 339

Try this simplified code

 i.e  $url='www.xyz.com';
            function urlModified($patterns, $replace, $url)
            {
              $patterns = array ('http://www.');
              $replace = array ('/^www\./');
              preg_replace($patterns, $replace, $url);
              return $url;
            }

Upvotes: 0

Julian Kuchlbauer
Julian Kuchlbauer

Reputation: 895

You could try a negative lookbehind:

(?!http://)www\.

Upvotes: 0

Indrasis Datta
Indrasis Datta

Reputation: 8606

Try this. This will check for not only HTTP, but also other protocols like HTTPS, FTP etc.

function addPrefix($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

echo addPrefix("http://ww.google.com");

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You can achieve that with a negative lookbehind:

'~(?<!://)www\.~'

See the regex demo

The (?<!://) lookbehind will fail a match if www. is preceded with :// thus avoiding the match in http://www. and https://www..

If you really want to avoid matching strings that have http:// only, add http or \bhttp before the : and use '~(?<!http://)www\.~'

Upvotes: 1

Related Questions