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

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

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?

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题