Page 1 of 1

Load a Text File and Replace Shorthand with PHP Variables

Posted: Tue Mar 22, 2011 11:43 am
by unifiedac
Hello,

Here is what I am trying to accomplish:

I have a text file that is being hand written. There are certain words that aren't being written, but are dynamically generated by the user. Instead of writing the words in the text file, a variable is put in its place. The text file may contain something like this:

Thank you for your purchase of $productName. We hope to see you back in the future!

I need PHP to load the text file, change $productName to

Code: Select all

<?php echo $productName; ?>
, so the value will load correctly when PHP displays the file.

So, to recap:

I have a text file that includes PHP variables, but is not written in PHP (shorthand). When the file loads, the shortand variables need to be converted into proper PHP syntax.

Any help is appreciated. Thanks!

Re: Load a Text File and Replace Shorthand with PHP Variable

Posted: Tue Mar 22, 2011 12:11 pm
by AbraCadaver
Something like this, but then you would need to eval() $result. Probably a better way:

Code: Select all

$result = preg_replace('/(\$[\w]+[\w\d]*)/', '</php echo $1; ?>', file_get_contents('file.txt'));
Maybe this also:

Code: Select all

// $var1 = 'something';
ob_start();
eval('echo "' . file_get_contents('file.txt') . '";');
$result = ob_get_clean();