Search code examples
phpstrstr

Match exactly with strstr


How can I use strstr to match the content of a variable exactly instead of just containing?

For example:

  • www.example.com/greenapples
  • www.example.com/redapples
  • www.example.com/greenapplesandpears

If my URL is set as a variable $myurl and I use the following..

if (strstr($myurl, 'redapples')) {
echo 'This is red apples';
    }

Then it also applies to the other URLs as they also include the word apples. How can I be specific?


Solution

  • Ehmm, just compare?

    if ('www.mydomain.com/greenapples' === $myurl) {
        echo 'green apples!';
    }
    

    update

    Without further info, I'm not sure if this fits your question, but if you're only interested in the last part of the URL and take into account the possibility that the URL contains a query-string (e.g. ?foo=bar&bar=foo), try something like this:

    // NOTE: $myurl should be INCLUDING 'http://'
    $urlPath = parse_url($myurl, PHP_URL_PATH);
    
    // split the elements of the URL 
    $parts = explode('/', $urlPath);
    
    // get the last 'element' of the path
    $lastPart = end($parts);
    
    
    switch($lastPart) {
        case 'greenapples':
            echo 'green!';
            break;
    
        case 'greenapplesandpears':
            echo 'green apples AND pears!';
            break;
    
        default:
            echo 'Unknown fruit family discovered!';
    
    }
    

    Documentation:

    http://www.php.net/manual/en/function.parse-url.php

    http://php.net/manual/en/function.end.php

    http://php.net/manual/en/control-structures.switch.php