1

I want to make this by the preg_replace:

$web = 'example.com';

I want the preg_replace make it http://www.example.com and if it http://example.com no problem. It should add http:// in it found in the URL.

I want do that is http:// not exist.

4
preg_replace("/^(?:http:\/\/)?(.*)/","http://$1",$web);
0
1

You don't need regular expressions for that. Just do $web = "http://$web".

1
  • The code has it is reported would add http:// even when it is already present. I agree there is no need to use regular expressions, in such cases. – apaderno Dec 19 '09 at 9:25
1
if( 0 !== strpos( $web, 'http://' ) )
{
    $web = 'http://'.$web;
}

Basically, you don't need a regular expression. What that should do is check to see if 'http://' is the first part of $web. If not, it will add 'http://' to the beginning of the string. Otherwise, it does nothing.

Another way to do that is to simply check if it's false... if( false === strpos( $web, 'http://' ) ) That should execute if the function fails. I don't think that's the best way to do it, however.

2
  • 1
    Rather than using strstr(), it would be better to use strpos(). – apaderno Dec 19 '09 at 8:36
  • @kiamlaluno - Thanks, I always forget about strpos(). Updated my answer to include that instead. – Jeff Rupert Dec 19 '09 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.