Don Alexander Eckford's String Replace Demo

This shows how one can find tokens within a text file and replace those tokens with PHP variables.

Original text

Thank you for registering for our conference.
Please print out and keep this receipt.

Title: [TITLE]

Cost: $ [COST]

The dates of the Conference are: [DATES]

Please also pay special attention to the below instructions for how to
access your conference and be sure to attend the orientation during
the week before it begins.

Please let us know in the orientation/support forum if there are
problems.  We want your experience to be educational and for the
technology to fade into the background.

Sincerely,

Don Alexander Eckford

Text after replacing tokens

Thank you for registering for our conference.
Please print out and keep this receipt.

Title: 2024 Conference on Technical Stuff

Cost: $ 249.95

The dates of the Conference are: Nov 18-25, 2024

Please also pay special attention to the below instructions for how to
access your conference and be sure to attend the orientation during
the week before it begins.

Please let us know in the orientation/support forum if there are
problems.  We want your experience to be educational and for the
technology to fade into the background.

Sincerely,

Don Alexander Eckford
 

CODE FOLLOWS

<?php
    
include('includes/header.php');

    
error_reporting(E_ALL);    // set error reporting to all
    
?>

    <h1>Don Alexander Eckford's String Replace Demo</h1>

    <p>
        This shows how one can find tokens within a text file and
        replace those tokens with PHP variables.
    </p>

    <?php
    
// here's the original text
    
echo "<p>Original text</p>";

    
$fcontents file('purchase_confirm.txt');  // get the file contents

    // Initialize an empty string to store the contents
    
$text '';

    
// Append the contents of the file to $text
    
foreach ($fcontents as $value) {
        
$text .= $value;
    }

    echo 
"<pre class='wide'>$text</pre>";

    
// Now replace the original text with the tokens we want to replace
    
$fcontents file('purchase_confirm.txt');  // Reload the original text

    
$title "2024 Conference on Technical Stuff";
    
$cost 249.95;
    
$dateinfo "Nov 18-25, 2024";

    
// Reset $text to store the updated content
    
$text '';

    echo 
"<br><p>Text after replacing tokens</p>";

    foreach (
$fcontents as $value) {
        
// Replace tokens in the text with dynamic variables
        
$value str_replace("[TITLE]"$title$value);
        
$value str_replace("[COST]"$cost$value);
        
$value str_replace("[DATES]"$dateinfo$value);
        
$text .= $value// Append the updated content to $text
    
}

    echo 
"<pre class='wide'>$text</pre>";

    include(
'includes/footer.php');
?>