dongyi0114 2017-01-01 12:27
浏览 60
已采纳

在逗号分隔的前缀列表中查找前缀的有效方法

I have a prefix stored in a variable

$prefix = “07”;

And coma separated list of prefixes stored in another variable (the list is provide by user using text box)

$allPrefixes = “07,03,+17”;

What is efficient way to check if the value stored in $prefix is one of the prefixes stored in $allPrefixes

  • 写回答

1条回答 默认 最新

  • douju2012 2017-01-01 12:39
    关注

    I'd go for a regex to match:

    $regex = "/(^|,)".$prefixe."(,|$)/";
    preg_match($regex,$allPrefixes);
    
    • On beginning of string before a comma,
    • between commas or
    • after comma, at end of string

    The above regex will match, for example, 07 but not 007.

    General knowledge, not applicable in this case:
    If 007 is not likely to appear, or prefixe is not likely to be a substring of any other prefixe, then you can use strpos($allPrefixes, $prefixe) > -1 instead, which is quite more efficient.

    However
    wrapping the $allPrefixes string between , and using strpos might be both efficient and accurate:

    strpos(",".$allPrefixes.",", ",".$prefixe.",")
    

    will match 07 but not 007

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?