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

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

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作