Search code examples
phpurlstrpos

Check if URL has certain string and match position with PHP


I've tried the following:

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

if (strpos($url,'austin') !== false) {
    echo 'Austin metro';
} else if (strpos($url,'georgetown') !== false) {
    echo 'Georgetown';
}

The issue is that this will match a URL that has austin anywhere. For example, the url for georgetown parameter is like this: www.domain.com/austin/georgetown/

So if url has austin/georgetown, would like to display georgetown option. Any suggestions? Thanks!


Solution

  • Go like this:

    $url = 'www.domain.com/austin/georgetown'; //output: georgetown
    
    if  (strpos($url,'georgetown') !== false && strpos($url,'austin') !== false) 
    {
        echo 'Georgetown';
    } 
    else if (strpos($url,'georgetown') !== false) 
    {
        echo 'Georgetown';
    } 
    else if (strpos($url,'austin') !== false)
    {
        echo 'austin';
    }
    

    first if condition is checking if austin and georgetown, both are there in the url, if yes georgetown will be printed. rest two conditions are just checking for austin and georgetown individually.

    See hear Php fiddle -> https://eval.in/715874

    Hope this helps.