2

Why does this not remove the http:// of the string?

$rurl = 'http://www.google.com';
$httpposi = strpos($rurl,'://');
echo $httpposi;
if($httpposi === true) {
$url=substr($rurl, strpos($rurl, '://') + 3);
echo $url;
} else {
$url=$rurl;
echo '3'.$url.'2';
}

echo $url;

5 Answers 5

3

Instead of:

if($httpposi === true) {

you need:

if($httpposi !== false) {

since if it is found in the string, it will return an offset as an integer, and you are doing a strict comparison and strictly an non-zero, positive integer is not equal to the boolean value true.

8 == true // true
8 === true // false, because 8 is not a boolean
0 == true // false, but we need to know if the needle is at position 0

so:

0 !== false // true, string was found
8 !== false // true, string was found
false !== false // false, string was not found

If the sequence is found at the beginning of the string, the falsy 0 will be returned, thus the need to strictly compare to false to know that it has not been found at all.

http://ideone.com/QXBs7

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Karim, if the thing I was looking for was at position 0, would your method still work?
@David19801 - yes, I've updated the explanation a bit. Will try to clarify some more.
1

As a few others already posted: Do not compare $httpposi with a boolean value! The return value of the strpos function is an integer value if it has found an occurence, but can return either false, 0 or "" if it didn't find your passed string.

For more information, take a look at the PHP.net docs!

Comments

1

Or you could use preg_replace instead and get rid of the problem another way:

$url=preg_replace('~^https?://~i','','http://www.google.com')

Caters for https as well. Just remove [s]? if that's not what you want. The /i is for ignoring case.

1 Comment

Thanks, forward slashes was a bad choice of course.. :-) Brackets around the s I would have kept myself for readability..
0
if($httpposi !== false) {

Comments

0

Change if($httpposi === true) { to if($httpposi) { or if($httpposi == true) {, since $httpposi = 4 isn't === to true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.