且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 PHP switch 语句检查字符串是否包含单词(但也可以包含其他单词)?

更新时间:2023-11-27 11:26:52

基于 this问题这个答案,我想出的解决方案(同时仍在使用案例选择)在下面.

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

您可以使用 stristr()strstr().在这种情况下,我选择使用 stristr() 的原因仅仅是因为它不区分大小写不敏感,因此更健壮.

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.

示例:

$linkKW = $_GET['kw'];

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

您也可以使用 stripos()strpos() 如果您愿意(谢谢,Fractaliste),虽然我个人觉得这更难阅读.与上述其他方法相同;我采用了不区分大小写的路线.

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.

示例:

$linkKW = $_GET['kw'];

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