Skip to content
Advertisement

PHP strpos() not acting as expected

I am attempting to clean up my URLS in the database, however I am literally having a brain-fart. This is PHP 101 level stuff, but I seriously cannot figure out what’s wrong with the following snip:

<?php

$domain = 'http://www.example.com';

echo "nne[31mBeginning Domain is: $domainn";

if (strpos($domain, '//')){
    $domain = explode( '//', $domain)[1];
    echo "ne[33mRemoving HTTPn";
}

echo "nne[35mAfter first IF domain is: $domainn";

if (strpos($domain, "www.")){
    echo "ne[33mREMOVING WWWn";
    $domain = explode( "www.", $domain)[1];
}

echo "nne[35mAfter second IF domain is: $domainn";

die("nne[31m$domainnn");

When run .. I am expecting a “clean” example.com — However my output looks like:

Beginning Domain is: http://www.example.com

Removing HTTP

After first IF domain is: www.example.com

After second IF domain is: www.example.com

www.example.com

Why is if (strpos($domain, "www.")){ not entering the if ?

Advertisement

Answer

Why not debug the code properly? strpos($domain, "www.") returns 0 as long as $domain starts with www, and that evaluates to false.

By properly checking whether strpos($domain, "www.") returns exactly false, you can fix your algorithm

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement