【问题标题】:Remove string after last hyphen [duplicate]在最后一个连字符后删除字符串[重复]
【发布时间】:2016-05-05 16:39:29
【问题描述】:

我想删除字符串中最后一个连字符及其后面的任何内容。看了之后,我发现了第一个连字符但不是最后一个连字符的东西:

$str = 'sdfsdf-sdfsdf-abcde';
$str = array_shift(explode('-', $str));

当前字符串

$str = 'sdfsdf-sdfsdf-abcde';

想要的结果

$str = 'sdfsdf-sdfsdf';

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    你可以使用这个preg_replace:

    $repl = preg_replace('/-[^-]*$/', '', $str);
    //=> sdfsdf-sdfsdf
    

    -[^-]*$ 将匹配 - 后跟 0 个或多个非连字符在行尾之前。

    【讨论】:

    • 使用implode/explode,您可以使用:$repl = implode('-', array_slice(explode('-', $str), -2));
    【解决方案2】:

    你已经接近了。只需使用array_pop() 而不是array_shift()。 array_pop() 删除数组的最后一个元素。当然,您需要稍后使用implode() 将字符串重新组合在一起。

    $arr = explode('-', $str);
    array_pop($arr);
    $str = implode('-', $arr);
    

    重要的是不要在一行中这样做,因为array_pop() 处理对数组的引用并修改它,然后只返回已删除的元素。

    其他答案还提到了一些其他可能的解决方案。

    【讨论】:

    • 是的,我犯了一个错误。 array_pop 返回已删除的元素 ;-) 已修复。
    【解决方案3】:

    你可以使用strrpos得到最后一个索引,然后使用substr得到想要的结果。

    $str = 'sdfsdf-sdfsdf-abcde';
    $pos = strrpos($str , "-");
    if ($pos !== false) {
       echo substr($str, 0, $pos);
    }
    

    【讨论】:

      【解决方案4】:

      这有点笨重,但对你有用:

      $str = 'sdfsdf-sdfsdf-abcde';
      $pieces = explode("-",$str);
      $count = count($pieces);
      
      for ($x = 0; $x <= $count - 2; $x++) {
         $desired_result .= $pieces[$x].'-';
      } 
      $desired_result = substr($desired_result, 0, -1);
      
      echo $desired_result;
      

      如果你有很多,你可以使用这个功能:

      function removeLast($str){
          $pieces = explode("-",$str);
          $count = count($pieces);
      
          for ($x = 0; $x <= $count - 2; $x++) {
             $desired_result .= $pieces[$x].'-';
          } 
          $desired_result = substr($desired_result, 0, -1);
      
          return $desired_result;
      }
      

      你叫它:

      $str = 'sdfsdf-sdfsdf-abcde';
      $my_result = removeLast($str);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        • 2011-12-15
        • 2021-01-18
        • 2013-08-11
        相关资源
        最近更新 更多