Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

// http://cz2.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:

http://cz2.php.net/manual/en/function.preg-replace-callback.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top