1

我在这里有这个小片段,false即使它满足if声明它也会返回。

$urls = $_POST['links'];
    trim($urls);
$urls = explode("\r\n",$urls);
foreach($urls as $url){
    trim($url);
    if(strpos($url,'http://') === false)
        $url = 'http://'.$url;
    $parse = parse_url($url, PHP_URL_HOST);
    if(($parse != 'site.com') || ($parse != 'www.site.com')) //problem here
        echo 'false:'.$parse.'<br>';
    else
        echo 'true:'.$parse;
}

输入来自文本区域:

http://site.com
site.com
http://www.site.com
www.site.com

输出:

true:site.com
true:site.com
false:www.site.com
false:www.site.com

你认为是什么问题?

4

4 回答 4

4

我不确定您的真正意图,但以下行绝对是错误的:

    if(($parse != 'site.com') || ($parse != 'www.site.com')) //problem here

这将始终返回 true,因为如果 parse 不是 'site.com' 则为 true,但如果 parse 不是 'www.site.com' 也为 true,因为它不能同时是它们两者,所以它必须永远是真实的。你的意思是 && 而不是 ||?即,逻辑与而不是逻辑或?

if(($parse != 'site.com') && ($parse != 'www.site.com')) 

编辑:实际上,如果您提出的问题是所需的行为,即 site.com 为 true,www.site.com 为 false,那么您只需要:

if ($parse == 'site.com')
{
    echo 'false:'.$parse;
}
else if ($parse == 'www.site.com')
{
    echo 'false:'.$parse;
}

或者也许这不是你真正想要的......

于 2012-05-02T09:15:25.237 回答
1

想想你在第二个 if 语句中使用的逻辑。不管是什么$parse,你总会落入if树枝。(也就是说,你永远不会落入else树枝。)

考虑以下替代方案:

// "Not A AND Not B"
if(($parse != 'site.com') && ($parse != 'www.site.com'))
// ...

// "Neither A nor B"
if(!(($parse == 'site.com') || ($parse == 'www.site.com')))
// ...

// "Either A or B"
if(($parse == 'site.com') || ($parse == 'www.site.com'))
    echo 'true:'.$parse;
else
    echo 'false:'.$parse.'<br>';
// Note here we also swapped the two branches.
于 2012-05-02T09:15:53.380 回答
0

将 if 行更改为:

if(($parse != 'site.com') && ($parse != 'www.site.com'))
于 2012-05-02T09:16:19.850 回答
0

替换这一行:

if(($parse != 'site.com') && ($parse != 'www.site.com'))
于 2012-05-02T09:24:15.307 回答