Reputation: 137
I have a function in which I want to delete parts of string from a string.
I want to delete the following substrings http://
ftp://
www.
www2.
which may be put inf front of a domain name.
Here's the code, but it's not working and I'm probably missing something very obvious.
private function GetValidDomainName($domain)
{
if(strpos($domain, 'http://'))
{
$this->domain = str_replace("http://", "", $domain);
}
if(strpos($domain, 'ftp://'))
{
$this->domain = str_replace("ftp://", "", $domain);
}
if(strpos($domain, 'www.'))
{
$this->domain = str_replace("www.", "", $domain);
}
if(strpos($domain, 'www2.'))
{
$this->domain = str_replace("www2.", "", $domain);
}
$dot = strpos($domain, '.');
$this->domain = substr($domain, 0, $dot);
$this->tld = substr($domain, $dot+1);
}
This is a first function which im using in the WHOIS check of the domain availability, I have function that will chech the available characters and allowed domain name lenghts etc later, they all work and the check itself works perfectly fine, but just this function is not doing what it's supposed to.
Upvotes: 1
Views: 142
Reputation: 157947
Theory:
You need to check with the strict comparison operator:
if(strpos($domain, 'http://') === 0)
... and so on.
That's because strpos
will return either the (first) postion of the occurrence in string or FALSE
if the sub string wasn't found.
In your case I expect the method will return either 0
meaning the sub string was found at the beginning or FALSE
if it was not found. Unless you are using the strict comparison operator both will be evaluated to FALSE
in PHP.
Praxis:
You don't need the strpos()
check at all because str_replace()
will only work if there is something to replace. You can just use this:
$this->domain = str_replace(array(
'http://', 'ftp://', 'www1', 'www2'
), '', $domain);
However this works only unless you can make sure that the urls will not contain http://
(or one of the others) multiple times. Meaning the following url would break:
http://test.server.org/redirect?url=http://server.org
To get it stable I would use preg_replace()
:
$pattern = '~^((http://|ftp://~|www1\.|www2\.))~'
$this->domain = preg_replace($pattern, '', $domain);
The pattern above will remove the sub strings only if they appear at the beginning of the string.
Upvotes: 1