如何使用 PHP switch 语句检查字符串是否包含单词(但也可以包含其他单词)? [英] How to use a PHP switch statement to check if a string contains a word (but can also contain others)?

查看:18
本文介绍了如何使用 PHP switch 语句检查字符串是否包含单词(但也可以包含其他单词)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP 开关,根据在页面 URL 的参数中传递的传入关键字来包含某些文件.

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

例如,URL 可以是:...page.php?kw=citroen%20berlingo%20keywords

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;

    } 
?>

如果关键字参数包含 berlingo,我想在第一种情况下包含berlingo.php 文件,但它不包含不必完全就是那个关键字.

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.

例如,如果关键字是 berlingo,我想包含 berlingo.php 文件,但如果它是 citroen,伯林戈.

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

如何使用 PHP case select(switch 语句)评估给定字符串是否包含值?

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

谢谢.

推荐答案

基于 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;
}

这篇关于如何使用 PHP switch 语句检查字符串是否包含单词(但也可以包含其他单词)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆