0

I have a string like

       "subscription link   :%list:subscription%
       unsubscription link :%list:unsubscription%
       ------- etc"

AND

I have an array like

    $variables['list']['subscription']='example.com/sub';
    $variables['list']['unsubscription']='example.com/unsub';
    ----------etc.

I need to replace %list:subscription% with $variables['list']['subscription'],And so on here list is first index and subscription is the second index from $variable .Is possible to use eval() for this? I don't have any idea to do this,please help me

3 Answers 3

2

Str replace should work for most cases:

foreach($variables as $key_l1 => $value_l1)
    foreach($value_l1 as $key_l2 => $value_l2)
        $string = str_replace('%'.$key_l1.':'.$key_l2.'%', $value_l2, $string);

Eval forks a new PHP process which is resource intensive -- so unless you've got some serious work cut out for eval it's going to slow you down.

Besides the speed issue, evals can also be exploited if the origin of the code comes from the public users.

Sign up to request clarification or add additional context in comments.

Comments

0

You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.

Then you include the php file in your current module and call the function which will return the array.

Comments

0

I would use regular expression and do it like that:

$stringWithLinks = "";
$variables = array();

// your link pattern, in this case
// the i in the end makes it case insensitive
$pattern = '/%([a-z]+):([a-z]+)%/i';

$matches = array();

// https://www.php.net/manual/en/function.preg-replace-callback.php
$stringWithReplacedMarkers = preg_replace_callback(
    $pattern, 
    function($mathces) {
        // important fact: $matches[0] contains the whole matched string
        return $variables[$mathces[1]][$mathces[2]];
    }, 
    $stringWithLinks);

You can obviously write the pattern right inside, I simply want to make it clearer. Check PHP manual for more regular expression possibilities. The method I used is here:

https://www.php.net/manual/en/function.preg-replace-callback.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.