Load a Text File and Replace Shorthand with PHP Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
unifiedac
Forum Newbie
Posts: 4
Joined: Tue Mar 22, 2011 11:34 am

Load a Text File and Replace Shorthand with PHP Variables

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

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

Post 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();
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply