Advice on Replacing Text

I want a file with placeholders:

{item}

text text text {something}

{otherItem}

What would be a good way to go about this?

Should I:

  1. file_get_contents into a string.
  2. str_replace(‘{item}’, ‘some data here’); etc… each of them.
  3. lastly, output the final result (Will be emailing it)

Or is there a simpler way to do this?

Curious, what kind of file are we talking about and how large?

It’s going to be very small, maybe 30 replacements MAX

You mean like a simple template? I have some code for that somewhere…

Try this:

$data = array(
‘name’ => ‘Bob’
);

$text = “Hello %%name%%!”;

$newtext = preg_replace(
“/%%(.*)%%/sUe”,
“(isset(\$data[‘\\1’])) ? \$data[‘\\1’] : ‘’”,
$text
);

echo $newtext;

That will echo “Hello Bob!”;

Hope that helps!

Hiya, thanks. I guess I will have to do something along these lines if str or preg are the only ways.

If it’s multiple pieces of replacements I would use str_replace and provide an array for the first two parameters.

I used file_get_contents and str_ireplace, something I made a bit ago. First functions before the actual class were things that might be useful to you, required some defined constants though.

function showHeader()
{
    include(TEMPLATE."header".TEMPLATE_EXT);
    return;
}

function showFooter()
{
    include(TEMPLATE."footer".TEMPLATE_EXT);
    return;
}

/**
 * Takes an error message, displays it through the error.php template, then calls the footer
 * and kills the script with exit().
 * 
 * @param string $errorMessage Error message you want the user to see.
 */
function showError($errorMessage)
{
    $template = new template("error");
    $template->fillBraces(array(
        "ERROR_MESSAGE" => $errorMessage,
        "ERROR_IMG"     => IMG_PATH."error.png"));
    $template->render();
    showFooter();
    exit();
    return;
}

class template
{
    protected $_viewContents;

    function __construct($viewName)
    {
        $this->_viewContents = file_get_contents(TEMPLATE.$viewName.TEMPLATE_EXT);
        return;
    }

    function sourceOf($fileName)
    {
        return @file_get_contents(TEMPLATE.$fileName.TEMPLATE_EXT);
    }

    function fillBraces($information, $replacement=NULL)
    {
        if (is_array($information))
        {
            foreach ($information as $key => $val)
            {
                $this->_viewContents = str_ireplace("{".$key."}", $val, $this->_viewContents);
            }
            return;
        } elseif ($replacement!=NULL)
        {
            $this->_viewContents = str_ireplace("{".$information."}", $replacement, $this->_viewContents);
            return;
        }
    }

    function render()
    {
        echo $this->_viewContents;
        return;
    }
}

/**
 * And finally, the example usage!
 * $template = new template("viewthread");
 * $template->fillBraces(array(
 *   "THREAD_TITLE"  => "How to bathe your chimpanzee",
 *   "THREAD_AUTHOR" => "Stuart Piazza"
 * ));
 * $template->render();
 */