PHP function to delete all between certain character(s) in string

前端 未结 5 1006
感情败类
感情败类 2020-11-27 17:21

I\'m interested in function delete_all_between($char1, $char2, $string) that will search given $string for $char1 and $char2 and, if such has been found, clear

5条回答
  •  迷失自我
    2020-11-27 17:32

    some invalid text!';
    $out = delete_all_between('', $string);
    print($out);
    
    function delete_all_between($beginning, $end, $string) {
      $beginningPos = strpos($string, $beginning);
      $endPos = strpos($string, $end);
      if ($beginningPos === false || $endPos === false) {
        return $string;
      }
    
      $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
    
      return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
    }
    

提交回复
热议问题