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

前端 未结 5 998
感情败类
感情败类 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:44

    Actually, I was looking for a function, which gives me simple and stable solution to grab out all the variables of TWIG template. The proposed regexps did not work well for many reasons so I decided to go by just erasing all the content between tags instead of counting tags ^_^.

    /**
         * deletes ALL the string contents between all the designated characters
         * @param $start - pattern start 
         * @param $end   - pattern end
         * @param $string - input string, 
         * @return mixed - string
         */
        function auxDeleteAllBetween($start, $end, $string) {
            // it helps to assembte comma dilimited strings
            $string = strtr($start. $string . $end, array($start => ','.$start, $end => chr(2)));
            $startPos  = 0;
            $endPos = strlen($string);
            while( $startPos !== false && $endPos !== false){
                $startPos = strpos($string, $start);
                $endPos = strpos($string, $end);
                if ($startPos === false || $endPos === false) {
                    $run = false;
                    return $string;
                }
                $textToDelete = substr($string, $startPos, ($endPos + strlen($end)) - $startPos);
                $string = str_replace($textToDelete, '', $string);
            }
            return $string;
        }
    
        /**
         * This function is intended to replace
         * //preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $this->_tplSubj, $matchesSubj);
         * which did not give intended results for some reason.
         *
         * @param $inputTpl
         * @return array
         */
        private function auxGetAllTags($inputTpl){
            $inputTpl = strtr($inputTpl, array('}}' => ','.chr(1), '{{' => chr(2)));
            return explode(',',$this->auxDeleteAllBetween(chr(1),chr(2),$inputTpl));
        }
    
    
    $template = '
    

    Dear {{jedi}},
    New {{padawan}} is waiting for your approval:

    ...'; print_r($this->auxGetAllTags($template));

    提交回复
    热议问题
    Register as{{register_as}}, user-{{level}}
    Name{{first_name}} {{last_name}}