if / and语句用于URL的strpos


if / and statement for URL with strpos

我有以下三个可能的url ..

  • www.mydomain.com/445/loggedin/?状态=空
  • www.mydomain.com/445/loggedin/?完整状态=
  • www.mydomain.com/445/loggedin/

www.mydomain.com/445部分是动态生成的,每次都是不同的,所以我不能做一个精确的匹配,我怎么能检测以下…

  • 如果$url包含loggedin但不包含/?status=空OR/?完整状态=

我所尝试的一切都失败了,因为无论它总是检测到已登录的部分..

if(strpos($referrer, '?status=empty')) {
echo 'The status is empty';
}
elseif(strpos($referrer, '?status=complete')) {
echo 'The status is complete';
}
elseif(strpos($referrer, '/loggedin/')) {
echo 'The status is loggedin';
}

将URL分割成若干段

$path = explode('/',$referrer);
$path = array_slice($path,1);

然后在这个数组上使用你的逻辑,你包含的第一个URL将返回这个:

Array ( [0] => 445 [1] => loggedin [2] => ?status=empty )

你可以这样做:

$referrer = 'www.mydomain.com/445/loggedin/?status=empty';
// turn the referrer into an array, delimited by the /
$url = explode('/', $referrer);
// the statuses we check against as an array
$statuses = array('?status=complete', '?status=empty');
// If "loggedin" is found in the url, and count the array_intersect matches, if the matches = 0, none of the statuses you specified where found
if( in_array('loggedin', $url) && count(array_intersect($url, $statuses)) == 0 )
{
    echo 'The user is logged in';
}
// if the complete status exists in the url
else if( in_array('?status=complete', $url) )
{
    echo 'The status is complete';
}
// if the empty status exists in the url
else if( in_array('?status=empty', $url) )
{
    echo 'The status is empty';
}

我建议你看看array_intersect,它很有用。

希望它能有所帮助,不确定这是否是最好的方法,但可能会激发你的想象力。

Strpos可能不是您想要使用的。你可以用stristr:

    if($test_str = stristr($referrer, '/loggedin/')) 
    {
        if(stristr($test_str, '?status=empty')) 
        {
            echo 'empty';
        }
        elseif (stristr($test_str, '?status=complete')) 
        {
            echo 'complete';
        } else {
            echo 'logged in';
        }
    }

但是使用正则表达式可能更容易/更好:

if(preg_match('/'/loggedin'/('?status=(.+))?$/', $referrer, $match)) 
{
    if(count($match)==2) echo "The status is ".$match[2];
    else echo "The status is logged in";
}