递归函数调用自身直到返回值

时间:2019-03-11 17:35:37

标签: php

我正在尝试检查字符串{}之间是否包含某些内容,以及它是否也将其替换为与之相关的内容,我遇到的问题是调用它本身

作为参考,假设我们有一个字符串https://technologyforthefuture.org/open-doors-challenge/?modalActive=true&video_id={user_video_id}&key-={user_affiliate_id}

我们将此字符串传递给以下函数ParseShortcodes()

当前会发生的情况是{user_video_id}将被注意到并被替换,然后这将是循环的结尾,并且将不会返回任何内容,因为代码正在等待$short为空以返回模板

我曾经在内部调用过ParseShortcodes(),但我认为这不是正确的方法,一定有更好的方法

function get_string_between($string, $start, $end){
            $string = ' ' . $string;
            $ini = strpos($string, $start);
            if ($ini == 0) return '';
            $ini += strlen($start);
            $len = strpos($string, $end, $ini) - $ini;
            return substr($string, $ini, $len);
        }

        function ParseShortcodes($template,$post_id){
            $short = get_string_between($template,"{","}");

            if($short == "user_affiliate_id"){
                global $wpdb;

                $query = $wpdb->get_row("SELECT * FROM wp_uap_affiliates WHERE uid=3");

                $short = $query->id;

                $template = str_replace("{user_affiliate_id}",$short,$template);
            }else if($short == "user_video_id"){
                $template = str_replace("{user_video_id}",$post_id,$template);
            }else if(empty($short)){
                return $template;
            }
        }

1 个答案:

答案 0 :(得分:0)

只需使用preg_replace_callback来查找全部 {words}并将其传递给您的回调:

 $templ = preg_replace_callback("/\{(\w+)\}/", "DoShortCodes", $templ);

这将调用该函数,仅传递user_video_id(或其他任何值),然后将其替换为源字符串。因此,回调可以调整为:

 function DoShortCodes($m) {
     switch($m[0]) {
         case "vidid": return "0";
         case "userthing": return db("SELECT ? as id", $x)->id;
         default: trigger_error("NO FINDY SHORTCODE");
     }
 }

哪个会替换步骤?

相关问题