0

Essentially at the moment I have a text file written in the script of another language. It will be stored as an element, and called to be served up as text when needed.

I want to manipulate this file with the following:

  1. Replace all the existing variables with a php array value storing that variable name. So if the variable looks like #foo, it becomes $variables['foo'].
  2. Create an array out of the entire file, making each line a row in the array.

The result is something like

return array(
  'first line of code which has a variable called ' . $variables['foo'] . 'in it',
  'second line...'
);

What would the simplest method be to go about this, and is there a way to cache the process, or should I perhaps just save and store the new file some where I can access it?

Thank you!

xtraorange
  • 1,456
  • 1
  • 16
  • 37

1 Answers1

1
  1. Use str_replace() (documentation: php.net) to replace all occurences

  2. Use explode() in the following way: How to put string in array, split by new line?

Caching.
I suggest you use View caching, a built in CakePHP helper.
To distinguish between the different caches for the different variable names, make sure you call the controller function with a parameter that discriminates among the variable names. E.g.:

public function generate_script($varname){
    // some code
}

If the discriminating variable is not known on calling the controller method (but is e.g. determined inside the controller method), you should look into the Cache API

Community
  • 1
  • 1
Bart Gloudemans
  • 1,201
  • 12
  • 27
  • Ok, so you soltuion was slightly different than I meant, but in fact would work just as well, and is probably a fair bit easier. As for the caching portion, you should understand that there will be multiple variables within the script, all being replaced, so I'm not sure that will work. I'll look through your suggested documentation though. – xtraorange Jul 28 '12 at 21:00
  • 1
    Regarding the caching: one of your goals is to find a unique cache key for each situation. So you should come up with a standard way to generate the key. For example: put all variable names in alphabetical order and consider that as the key. Along that same line you could think about standardizing the way the method is called, so the URL becomes unique and cacheable also for multiple variable names. – Bart Gloudemans Jul 28 '12 at 21:26