douzhou7037
2019-07-03 12:06
浏览 260
已采纳

检查字符串是否存在于两个字符串列表中(以逗号分隔)

I want to check if a given 2-character value (my input: $string), exists inside any of my two separate lists, of possible matching values:

One list is dynamic (it will be read from my DB), and the values in it are separated by commas, with space after each comma:

It can be for example:

$dynamic_list="AA, AB, BA"
$dynamic_list="BC"
$dynamic_list="" (Empty)

The second list is a static list that I will maintain myself, and should be within the script itself.

I’m not sure how to build it. Maybe just define a variable like:

$static_list="MC,JL,EO";

If the string matches any of the strings in any of those lists, I just want to output that string, otherwise output "no match".

What is the best and fast way to do this?

图片转代码服务由CSDN问答提供 功能建议

我想检查一个给定的2个字符的值(我的输入: $ string ),存在于我的两个单独列表中的任何一个可能的匹配值:

一个列表是动态的(它将从我的数据库中读取),其中的值用逗号分隔 ,每个逗号后面有空格:

可以是例如:

  $ dynamic_list =“AA,AB,BA”
  $ dynamic_list =“BC”
 $ dynamic_list =“”(空)
   
 
 

第二个列表是我自己维护的静态列表,应该在 脚本本身。

我不确定如何构建它。 也许只需定义一个变量,如:

  $ static_list =“MC,JL,EO”; 
   
 
 

如果 字符串匹配任何这些列表中的任何字符串,我只想输出该字符串,否则输出“不匹配”。

最好和最快的方法是什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • douguanyan9928 2019-07-03 12:21
    最佳回答

    Concatenate the two strings with the same delimiter that the strings use, and check as normal.

    Performing aditional string or array manipulations are needless overhead.

    Code: (Demo)

    $dynamic_list = "AA, AB, BA";
    $static_list = "MC,JL,EO";
    
    $search = "JL";
    
    if (strpos($dynamic_list . ',' . $static_list, $search) !== false) {
        echo 'found';
    } else {
        echo 'not found';
    }
    

    But, really, you should check the static string first. Then only bother making a trip to the database IF you don't have a match in the static string.

    As for querying, you might count the number of rows where the search string is found by LOCATE() -- since you don't need the data, just confirmation of a match.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题