I am trying to check if a string contains something between {} and if it does replace it with what it relates too the issue I am having with this is calling it to itself

For reference lets assume we have a string https://technologyforthefuture.org/open-doors-challenge/?modalActive=true&video_id={user_video_id}&key-={user_affiliate_id}

We pass this string into the below function ParseShortcodes()

What will happen currently is {user_video_id} will be noticed and replaced and then that will be the end of the loop and nothing will be returned because the code is waiting for $short to be empty to return template

I had though about calling ParseShortcodes() within itself but I dont think this is the right way to do this there must be some better way

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 Answers

mario On Best Solutions

Just use preg_replace_callback to look up all {words} and pass it to your callback:

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

That will invoke the function, passing only user_video_id (or whatever), and replacing it in the source string with its substitute. Thus the callback can be trimmed down to:

 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");

Which obsoletes the replacement step.