How to use a PHP switch statement to check if a string contains a word (but can also contain others)?
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;}
Since in a switch
statement only a simple equality testing will be performed it won't help you much here. You need to run the string through a string matching function, best suited of which is strpos
. The straight forward answer is:
if (strpos($_GET['kw'], 'berlingo') !== false) { include 'berlingo.php';} else if (strpos($_GET['kw'], 'c4') !== false) { include 'c4.php';} … and so on …
The more elegant solution would be something like this:
$map = array('berlingo' => 'berlingo.php', 'c4' => 'c4.php', …);foreach ($map as $keyword => $file) { if (strpos($_GET['kw'], $keyword) !== false) { include $file; break; }}
Or, if the correspondence between the keyword and the file is always 1:1:
$keywords = array('berlingo', 'c4', …);foreach ($keywords as $keyword) { if (strpos($_GET['kw'], $keyword) !== false) { include "$keyword.php"; break; }}
You can use strpos function as:
if(strpos($_GET['kw'],'berlingo') !== false) { include 'berlingo.php';}if(strpos($_GET['kw'],'c4') !== false) { include 'c4.php';}