代码之家  ›  专栏  ›  技术社区  ›  Marco Demaio

PHP substr在某个字符之后,一个substr+strpos优雅的解决方案?

  •  15
  • Marco Demaio  · 技术社区  · 14 年前

    假设我想把针头烧焦后的所有烧焦都还给你 'x' 发件人:

    $source_str = "Tuex helo babe"

    if( ($x_pos = strpos($source_str, 'x')) !== FALSE )
       $source_str = substr($source_str, $x_pos + 1);
    

    你知道一种更好/更聪明(更优雅的方式)的方法吗?

    如果不使用regexp,它将不会变得更优雅,而且可能也会更慢。

    不幸的是,我们不能:

    $source_str = substr(source_str, strpos(source_str, 'x') + 1);
    

    “x” 找不到 strpos 回报 FALSE (而不是 -1 错误的 将计算为零,并且第一个字符将始终被截断。

    5 回复  |  直到 10 年前
        1
  •  12
  •   Gumbo    14 年前

    你的第一个方法是好的:检查 x 包含在 strpos substr .

    但你也可以用 strstr

    strstr($str, 'x')
    

    但是当这返回子字符串开始时 具有 ,使用 子序列 在之后得到零件 :

    if (($tmp = strstr($str, 'x')) !== false) {
        $str = substr($tmp, 1);
    }
    

    但这要复杂得多。所以用你的 strpos公司 而是靠近。

        2
  •  5
  •   Alix Axel    14 年前

    // helo babe
    echo preg_replace('~.*?x~', '', $str);
    
    // Tuex helo babe
    echo preg_replace('~.*?y~', '', $str);
    

    但你可以试试这个:

    // helo babe
    echo str_replace(substr($str, 0, strpos($str, 'x')) . 'x', '', $str);
    
    // Tuex helo babe
    echo str_replace(substr($str, 0, strpos($str, 'y')) . 'y', '', $str);
    
        3
  •  0
  •   dev-null-dweller    14 年前
    if(strpos($source_str, 'x') !== FALSE )
       $source_str = strstr($source_str, 'x');
    

    x 一开始:

    if(strpos($source_str, 'x') !== FALSE )
       $source_str = substr(strstr($source_str, 'x'),1);
    
        4
  •  0
  •   William George    10 年前

    ltrim(strstr($source_str, $needle = "x") ?: $source_str, $needle);

    这个 ternary operator 在5.3中进行了修改,使其能够工作。

    自PHP 5.3以来,可以省略三元运算符的中间部分。表达式expr1?:如果expr1的计算结果为TRUE,则expr3返回expr1,否则返回expr3。

    ltrim 将修剪字符串开头的多个匹配字符。

        5
  •  -1
  •   Rajesh    10 年前

    在末尾附加一个“-” $item 所以它总是在“-”之前返回字符串 $项 首次出现的位置

    substr($item,0,strpos($item.'-','-'))