Re: variable placeholders in a text file
| From: | Stuart Dallas | Date: | Mon, 31 Dec 2012 19:59:50 +0000 |
| Subject: | Re: variable placeholders in a text file | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-319979@lists.php.net to get a copy of this message | ||
Please excuse the top post, but this may be helpful: http://stut.net/2008/10/28/snippet-simple-templates-with-php/
-Stuart
--
Sent from my leaf blower
On 31 Dec 2012, at 19:59, Ashley Sheridan <ash@ashleysheridan.co.uk> wrote:
> On Mon, 2012-12-31 at 13:39 -0600, Nelson Green wrote:
>
>> Hello,
>>
>> I have created a simple function that prints a personalized greeting by reading
>> the greeting contents from a file. I pass the user's name to the function,
>> and the function reads the file contents into a string variable. I am then
>> using str_replace to replace the word USER in the string with the user's
>> name that was passed to the function. Then the function correctly prints
>> the personalized greeting as I wish.
>>
>> My question is, is there another way to do something similar, such as
>> embedding a variable name directly into the text file? In other words,
>> instead of my text file reading:
>>
>> Hello USER ...
>>
>> Can I do something like this:
>>
>> Hello $user_name ...
>>
>> and then write my function to replace $user_name with the passed
>> parameter prior to printing?
>>
>> The reason I ask is because I am going to want to do three substitutions,
>> and I'd rather not do three str_replace calls if I don't have to. Plus the
>> latter seems to be a more robust way of making the changes.
>>
>> Thanks, and apologies if this has been asked before and I missed it. I'm
>> just not sure how to phrase this for a search engine.
>>
>> Nelson
>
>
> You could use an existing templating solution, like Smarty, although for
> what you want to do it might be overkill. A few str_replace() calls
> shouldn't produce too much overhead, but it depends on the size of the
> text string in question. If it's just a couple of paragraphs of text, no
> problem, something closer to a whole chapter of a book will obviously be
> more expensive.
>
> You could try eval() on the block of text, but if you do, be really
> careful about what text you're using. I wouldn't recommend this if
> you're using any text supplied by a user. As a last option, you could
> have the text stored as separate parts which you join together in one
> string later. This might be less expensive in terms of processing power
> required, but it also makes maintenance more of a hassle later.
>
>
> Thanks,
> Ash
> http://www.ashleysheridan.co.uk
>
>