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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4175910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:12:53  来源:igfitidea点击:

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

phpstringswitch-statementurl-parametersphp-include

提问by sebastian

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

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

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

例如,URL 可以是: ...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.phpfile if the keyword parameter containsberlingo, but it doesn't have to be exactlythat keyword alone.

在第一种情况下,我想要做的是berlingo.php如果关键字参数包含文件,则包含文件berlingo,但它不必仅该关键字。

For example, I want to include the berlingo.phpfile if the keyword is berlingo, but alsoif it's citroen berlingo.

例如,我想包括的berlingo.php文件,如果关键字berlingo,但如它的citroen berlingo

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

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

Thanks.

谢谢。

回答by baacke

Based on this questionand 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.

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

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-insensitiveroute.

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

Example:

例子:

$linkKW = $_GET['kw'];

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

回答by deceze

Since in a switchstatement 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:

由于在switch语句中只会执行简单的相等性测试,因此在这里对您没有太大帮助。您需要通过字符串匹配函数运行字符串,最适合的是strpos. 直接的答案是:

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:

或者,如果关键字和文件的对应关系始终是 1:1:

$keywords = array('berlingo', 'c4', …);
foreach ($keywords as $keyword) {
    if (strpos($_GET['kw'], $keyword) !== false) {
        include "$keyword.php";
        break;
    }
}

回答by chris

$keywords = array('berlingo', 'c4');
foreach($keywords as $keyword)
  if(strpos($_GET['kw'], $keyword) !== FALSE)
    include("$keyword.php");

I wouldn't recommend including php files based on user input though.

我不建议包含基于用户输入的 php 文件。

回答by AlexIL

You can also use regular expression in switch -> case:

您还可以在 switch -> case 中使用正则表达式:

<?php

    $kw = filter_input(INPUT_GET, "kw");

    switch($kw){

        case (preg_match('/*berlingo*/', $kw) ? true : false):     
            include 'berlingo.php';
            break;

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

    } 
?>

回答by codaddict

You can use strposfunction as:

您可以将strpos函数用作:

if(strpos($_GET['kw'],'berlingo') !== false) {
 include 'berlingo.php';
}
if(strpos($_GET['kw'],'c4') !== false) {
 include 'c4.php';
}

回答by user1718888

In my opinion, it's a code smellif you're including scripts via GET variables, but you can do this elegantly using a value class with methods whose logic return the value object itself if true.

在我看来,如果您通过 GET 变量包含脚本,这是一种代码异味,但是您可以使用带有方法的值类优雅地做到这一点,这些方法的逻辑返回值对象本身(如果为真)。

The idea is to keep in mind that a switchstatement will execute any code where $switch == $case (a loose match). So just create methods which either return $this, or nothing at all.

这个想法是要记住,switch语句将执行 $switch == $case (松散匹配)的任何代码。因此,只需创建返回$this或什么都不返回的方法。

Example:

例子:

class Haystack {
    public $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function contains($needle):
    {
        if (strpos($this->value, $needle) !== false)
            return $this;
    }
}

$kw = new Haystack($_GET['kw']);

switch ($kw) {
    case $kw->contains('berlingo'):
        require_once 'berlingo.php';
    case $kw->contains('c4'):
        require_once 'c4.php';
}

You can, of course, generously garnish this code with typehints. If you do, and are not using a version of PHP which supports nullable return types (ie a method signature of public function contains(string $substring): ?Haystack) then your class would have to elaborate to reflect that.

当然,您可以用类型提示慷慨地装饰此代码。如果您这样做,并且不使用支持可为空返回类型(即 的方法签名public function contains(string $substring): ?Haystack)的 PHP 版本,那么您的类将必须详细说明以反映这一点。

Example:

例子:

final class Haystack {
    private $value;
    private $isMain;

    public function __construct(string $value, bool $isMain = true)
    {
        $this->value = $value;
        $this->isMain = $isMain;
    }

    final public function contains($needle): Haystack
    {
        if (strpos($this->value, $needle) !== false)
            return $this;
        return new Haystack($needle, false);
    }
}

This way, if your explicit matching logic fails inside the method, if for some reason new Haystack($_GET['kw']) == new Haystack($needle);is true, the non-matching property "$isMain" will ensure they are not evaluated as equal.

这样,如果您的显式匹配逻辑在方法内部失败,如果由于某种原因new Haystack($_GET['kw']) == new Haystack($needle);为真,则非匹配属性“$isMain”将确保它们不被评估为相等。

Again, I would re-examine why you'd want to do this in the first place for this particular situation; traditionally, Composeris a dependency management tool which would be used to include various scripts you need via a PSR autoload standard. That in combination with a Router library would probably be the most useful to address your actual needs.

再次,我会重新检查为什么您首先要针对这种特殊情况执行此操作;传统上,Composer是一种依赖管理工具,可用于通过 PSR 自动加载标准包含您需要的各种脚本。与 Router 库结合使用可能最能满足您的实际需求。

回答by mOrloff

I know this is WAY after the fact, but just as an aside, one can always avoid the loop altogether if expecting a 1:1 relationship.

我知道这是事后的方式,但顺便说一句,如果期望 1:1 的关系,人们总是可以完全避免循环。

Something along the lines of:

类似的东西:

$map = array('berlingo' => 'berlingo.php', 'c4' => 'c4.php', …);

if( !isset( $map[$_GET['kw']] ))
    throw new Exception("Blah!!");

include $map[$_GET['kw']];

...just sharing as an FYI for newbies.

...只是作为新手的FYI分享。

回答by Core Xii

strpos()is one for checking if a string contains another string.

strpos()用于检查一个字符串是否包含另一个字符串。

There are other functionsfor checking similarity of strings, etc.

还有其他函数用于检查字符串的相似性等。

A switchwon't do, though, since it compares static expressions against a single value. You'll have to use ifs.

switch但是,A不会这样做,因为它将静态表达式与单个值进行比较。你将不得不使用ifs。