How to use a PHP switch statement to check if a string contains a word (but can also contain others)?

sebastian picture sebastian · Nov 14, 2010 · Viewed 35.2k times · Source

I'm using a PHP switch to include certain files based on the incoming keywords passed in a parameter of the page's URL.

The URL, for example, could be: ...page.php?kw=citroen%20berlingo%20keywords

Inside the page, I'd like to use something like this:

<?
    switch($_GET['kw']){

        case "berlingo":     
            include 'berlingo.php'
            break;
        case "c4":
            include 'c4.php';
            break;

    } 
?>

What I want to do in the first case is include the berlingo.php file if the keyword parameter contains berlingo, but it doesn't have to be exactly that keyword alone.

For example, I want to include the berlingo.php file if the keyword is berlingo, but also if it's citroen berlingo.

How can I evaluate if a given string contains a value using a PHP case select (switch statement)?

Thanks.

Answer

baacke picture baacke · Apr 19, 2013

Based on this question and this answer, the solutions I've come up with (while still using a case select) are below.

You can use either stristr() or strstr(). The reason I chose to use stristr() in this case is simply because it's case-insensitive, and thus, is more robust.

Example:

$linkKW = $_GET['kw'];

switch (true){
   case stristr($linkKW,'berlingo'):
      include 'berlingo.php';
      break;
   case stristr($linkKW,'c4'):
      include 'c4.php';
      break;
}

You could also use stripos() or strpos() if you'd like (thanks, Fractaliste), though I personally find this more difficult to read. Same deal as the other method above; I went the case-insensitive route.

Example:

$linkKW = $_GET['kw'];

switch (true){
   case stripos($linkKW,'berlingo') !== false:
      include 'berlingo.php';
      break;
   case stripos($linkKW,'c4') !== false:
      include 'c4.php';
      break;
}