【问题标题】:replacing/deleting substring from a string从字符串中替换/删除子字符串
【发布时间】:2014-02-03 18:46:38
【问题描述】:

我有一个函数,我想从字符串中删除部分字符串。

我想删除以下子字符串http://ftp://www.www2.,这些子字符串可能放在域名前面。

这是代码,但它不起作用,我可能遗漏了一些非常明显的东西。

    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);
}

这是我在域名可用性的 WHOIS 检查中使用的第一个功能,我有一个功能可以在以后检查可用字符并允许域名长度等,它们都可以正常工作,并且检查本身工作得很好,但只是这个函数没有做它应该做的事情。

【问题讨论】:

    标签: php regex string str-replace


    【解决方案1】:

    理论:

    您需要与strict comparison operator联系:

    if(strpos($domain, 'http://') === 0) 
    

    ... 等等。

    这是因为strpos 将返回字符串中出现的(第一个)位置,如果未找到子字符串,则返回FALSE

    在您的情况下,我希望该方法将返回0,这意味着在开头找到了子字符串,如果没有找到,则返回FALSE。除非您使用严格的比较运算符,否则两者都将在 PHP 中计算为 FALSE

    实践:

    您根本不需要strpos() 检查,因为str_replace() 仅在有要替换的东西时才有效。你可以用这个:

    $this->domain = str_replace(array(
        'http://', 'ftp://', 'www1', 'www2'
    ), '', $domain);
    

    但这仅在您可以确保网址不会多次包含http://(或其他网址之一)的情况下才有效。这意味着以下网址会中断:

    http://test.server.org/redirect?url=http://server.org
    

    为了让它稳定,我会使用preg_replace():

    $pattern = '~^((http://|ftp://~|www1\.|www2\.))~'
    $this->domain = preg_replace($pattern, '', $domain);
    

    上面的模式只会删除出现在字符串开头的子字符串。

    【讨论】:

    • 感谢您的帮助。第一个几乎可以工作,但由于某些原因,它不会从“www”中删除点。或“www2.”,但它根本不适用于 http:// 和 ftp://。 preg_replace 给了我以下错误Warning: preg_replace(): Unknown modifier '|'
    • 检查我的更新,我错过了一些().. 现在应该可以工作了。需要从键盘紧急离开。也许以后可以帮忙。
    • 是的,快到了,我现在用第一种方法得到了这个。在http://www. 的情况下它不起作用,但即使我为它创建else if,它似乎仍然不起作用。 pattern 仍然给我穿,并允许www.www2.。删除这些内容很重要。