2013-04-12 54 views
0

URL我有以下三种可能的网址..如果/和语句与strpos

  • www.mydomain.com/445/loggedin/?status=empty
  • www.mydomain.com/445 /的loggedIn /?状态=完全
  • www.mydomain.com/445/loggedin/

的www.mydomain.com/445部分是动态生成的,并且每次都不同,所以我不能做一个完全匹配,我如何检测以下...

  • 如果$ URL中包含的loggedIn但不包含任何/?状态=空或/?状态=完全

一切我尝试失败,因为不管是什么,它会永远检测记录的部分..

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

回答

1

片了URL成段

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

然后,只需用你的逻辑阵列,冷杉包括你会回到这件T网址:

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

你可以做这样的事情:

$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,这是非常有用的。

希望它有帮助,不知道这是否是最好的方式,但可能会激发你的想象力。

0

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