代码之家  ›  专栏  ›  技术社区  ›  Timo Huovinen

php:写这个的捷径?

  •  0
  • Timo Huovinen  · 技术社区  · 15 年前

    写这篇文章最短的方法是什么?

    if(strpos($haystack, $needle)!==false){
        $len = strpos($haystack, $needle)+strlen($needle);
    }else{
        $len = 0;
    }
    

    我记得我在某个地方看到了一个快捷方式,可以同时检查和设置一个变量。

    6 回复  |  直到 15 年前
        1
  •  5
  •   deceze    15 年前
    $len = 0;
    if(($pos = strpos($haystack, $needle)) !== false) {
        $len = $pos + strlen($needle);
    }
    

    我建议不要用三元的 ?: 接线员,即使更短。

        2
  •  2
  •   Pierre-Antoine LaFayette    15 年前
    $len = strpos($haystack, $needle);
    $len = ($len !== false) ? $len + strlen($needle) : 0;
    
        3
  •  1
  •   Your Common Sense    15 年前
    $len=strpos($haystack, $needle);
    if($len !== FALSE) {
        $len +=  strlen($needle);
    }
    

    而且,在我看来,三元运算符对可读性的影响是可怕的。

        4
  •  0
  •   Daff    15 年前

    它被称为 tenary operator 可以这样使用:

    $len = strpos($haystack, $needle) ? strpos($haystack, $needle)+strlen($needle) : 0;
    

    不过,你应该小心使用它,因为它会使一些表达式很难阅读。

        5
  •  0
  •   Ham Vocke    15 年前
    $len = strpos($haystack, $needle) ? strpos($haystack, $needle)+strlen($needle) : 0;
    

    参见 Ternary Operation .

        6
  •  0
  •   intuited    15 年前

    另一种方法:

    $len = strlen(preg_replace('/(.*?'.preg_quote($needle,'/').')?.*/', '$1', $haystack));
    

    可能更慢,内存更密集,但它确实需要更少的输入。所以这是否真的是一个捷径取决于定义。如果您对三元运算符和求值条件内的赋值过敏,则它确实提供了一个有效的选项。

    你也可以

    $len = preg_match('/'.preg_quote($needle,'/').'()/', $haystack, $m, PREG_OFFSET_CAPTURE)? $m[1][1] : 0
    

    尽管使用preg_u函数来搜索固定字符串还是有点浪费资源。

    推荐文章