Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 924321
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T19:20:01+00:00 2026-05-15T19:20:01+00:00

I’m writing code to recursively replace predefined variables from inside a given string. The

  • 0

I’m writing code to recursively replace predefined variables from inside a given string. The variables are prefixed with the character ‘%’. Input strings that start with ‘^’ are to be evaluated.

For instance, assuming an array of variables such as:

$vars['a'] = 'This is a string';  
$vars['b'] = '123';  
$vars['d'] = '%c';  // Note that $vars['c'] has not been defined
$vars['e'] = '^5 + %d';  
$vars['f'] = '^11 + %e + %b*2';  
$vars['g'] = '^date(\'l\')';  
$vars['h'] = 'Today is %g.';  
$vars['input_digits'] = '*****';  
$vars['code'] = '%input_digits';  

The following code would result in:

a) $str = '^1 + %c';  
   $rc = _expand_variables($str, $vars);  
  // Result: $rc == 1 

b) $str = '^%a != NULL';  
   $rc = _expand_variables($str, $vars);  
   // Result: $rc == 1  

c) $str = '^3+%f + 3';  
   $rc = _expand_variables($str, $vars);  
   // Result: $rc == 262  

d) $str = '%h';  
   $rc = _expand_variables($str, $vars);  
   // Result: $rc == 'Today is Monday'  

e) $str = 'Your code is: %code';  
   $rc = _expand_variables($str, $vars);  
   // Result:  $rc == 'Your code is: *****'  

Any suggestions on how to do that? I’ve spent many days trying to do this, but only achieved partial success. Unfortunately, my last attempt managed to generate a ‘segmentation fault’!!

Help would be much appreciated!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T19:20:02+00:00Added an answer on May 15, 2026 at 7:20 pm

    Note that there is no check against circular inclusion, which would simply lead to an infinite loop. (Example: $vars['s'] = '%s'; ..) So make sure your data is free of such constructs.
    The commented code

        // if(!is_numeric($expanded) || (substr($expanded.'',0,1)==='0'
        //            && strpos($expanded.'', '.')===false)) {
    ..
        // }
    

    can be used or skipped. If it is skipped, any replacement is quoted, if the string $str will be evaluated later on! But since PHP automatically converts strings to numbers (or should I say it tries to do so??) skipping the code should not lead to any problems.
    Note that boolean values are not supported! (Also there is no automatic conversion done by PHP, that converts strings like ‘true’ or ‘false’ to the appropriate boolean values!)

        <?
        $vars['a'] = 'This is a string';
        $vars['b'] = '123';
        $vars['d'] = '%c';
        $vars['e'] = '^5 + %d';
        $vars['f'] = '^11 + %e + %b*2';
        $vars['g'] = '^date(\'l\')';
        $vars['h'] = 'Today is %g.';
        $vars['i'] = 'Zip: %j';
        $vars['j'] = '01234';
        $vars['input_digits'] = '*****';
        $vars['code'] = '%input_digits';
    
        function expand($str, $vars) {
            $regex = '/\%(\w+)/';
            $eval = substr($str, 0, 1) == '^';
            $res = preg_replace_callback($regex, function($matches) use ($eval, $vars) {
                if(isset($vars[$matches[1]])) {
                    $expanded = expand($vars[$matches[1]], $vars);
                    if($eval) {
                        // Special handling since $str is going to be evaluated ..
    //                    if(!is_numeric($expanded) || (substr($expanded.'',0,1)==='0'
    //                            && strpos($expanded.'', '.')===false)) {
                            $expanded = "'$expanded'";
    //                    }
                    }
                    return $expanded;
                } else {
                    // Variable does not exist in $vars array
                    if($eval) {
                        return 'null';
                    }
                    return $matches[0];
                }
            }, $str);
            if($eval) {
                ob_start();
                $expr = substr($res, 1);
                if(eval('$res = ' . $expr . ';')===false) {
                    ob_end_clean();
                    die('Not a correct PHP-Expression: '.$expr);
                }
                ob_end_clean();
            }
            return $res;
        }
    
        echo expand('^1 + %c',$vars);
        echo '<br/>';
        echo expand('^%a != NULL',$vars);
        echo '<br/>';
        echo expand('^3+%f + 3',$vars);
        echo '<br/>';
        echo expand('%h',$vars);
        echo '<br/>';
        echo expand('Your code is: %code',$vars);
        echo '<br/>';
        echo expand('Some Info: %i',$vars);
        ?>
    

    The above code assumes PHP 5.3 since it uses a closure.

    Output:

    1
    1
    268
    Today is Tuesday.
    Your code is: *****
    Some Info: Zip: 01234
    

    For PHP < 5.3 the following adapted code can be used:

    function expand2($str, $vars) {
        $regex = '/\%(\w+)/';
        $eval = substr($str, 0, 1) == '^';
        $res = preg_replace_callback($regex, array(new Helper($vars, $eval),'callback'), $str);
        if($eval) {
            ob_start();
            $expr = substr($res, 1);
            if(eval('$res = ' . $expr . ';')===false) {
                ob_end_clean();
                die('Not a correct PHP-Expression: '.$expr);
            }
            ob_end_clean();
        }
        return $res;
    }
    
    class Helper {
        var $vars;
        var $eval;
    
        function Helper($vars,$eval) {
            $this->vars = $vars;
            $this->eval = $eval;
        }
    
        function callback($matches) {
            if(isset($this->vars[$matches[1]])) {
                $expanded = expand($this->vars[$matches[1]], $this->vars);
                if($this->eval) {
                    // Special handling since $str is going to be evaluated ..
                    if(!is_numeric($expanded) || (substr($expanded . '', 0, 1)==='0'
                            && strpos($expanded . '', '.')===false)) {
                        $expanded = "'$expanded'";
                    }
                }
                return $expanded;
            } else {
                // Variable does not exist in $vars array
                if($this->eval) {
                    return 'null';
                }
                return $matches[0];
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 449k
  • Answers 449k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I would parse your string using Postfix notation (or Polish… May 15, 2026 at 8:15 pm
  • Editorial Team
    Editorial Team added an answer I would first take a look at the Microsoft Sync… May 15, 2026 at 8:15 pm
  • Editorial Team
    Editorial Team added an answer I'm not sure if this is the cause but... first… May 15, 2026 at 8:15 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.