Page 1 of 1

str_replace problem

Posted: Mon Nov 14, 2005 6:53 pm
by Sphenn
Hi everyone.

I have the following code in a file that is supposed to parse a template file

Code: Select all

<?php
class template
{
	public $_tpl_data = array();
	
	public function __construct($template_root)
	{
		$this->setup($template_root);
	}

	/**
 	* function: setup($template_root)
	* Sets up the template root dir.  
	*
	* @param		$template_root	The root dir of the template files.  
	* @return	No value.  
	*
	*/

	public function setup($template_root)
	{
		$this->_tpl_data['root_dir'] = $template_root;
	}

	/**
	 * function: set_file($filename)
	 * Sets the file that we're going to use.  
	 *
	 * @param 	$filename	The file to be opened.  
	 * @return 	No value.  
	 *
	 */
	
	public function set_file($filename)
	{
		$handle = fopen($this->_tpl_data['root_dir'] . $filename, "r+");
		$this->_tpl_data['file_contents'] = fread($handle, filesize($this->_tpl_data['root_dir'] . $filename));
		fclose($handle);
	}
	
	/**
	 * function: assign()
	 * Assigns data to template variables.  
	 *
	 * @param 	$key	The tpl placeholder that will be replaced.  
	 * @param 	$data	The data which will replace the tpl placeholder.  
	 * @return 	No value.  
	 *
	 */
	
	public function assign($key, $data)
	{
		echo $this->_tpl_data['file_contents'];
		$this->_tpl_data['vars'][$key] = $data;
		preg_match_all('#\{(.*?)\}#', $this->_tpl_data['file_contents'], $matches);
		foreach( $matches[1] as $found )
		{
			if( $key == $found )
			{
				str_replace($matches[0][0], $data, $this->_tpl_data['file_contents']);
			}
		}
	}
	
}

?>
I have the following code that uses this class

Code: Select all

$template->set_file('test.html');
$template->assign('ASDF', 'Some stuff');
And it's parsing this template file

Code: Select all

<html>
<head>
<title>
</title>
</head>
<body>
{ASDF}
</body>
</html>
However, for some reason, when I echo out the result, it's the same as before the operation.

Can anyone help?

Thanks,

Sphenn

Posted: Mon Nov 14, 2005 7:08 pm
by josh
Replace:

Code: Select all

preg_match_all('#\{(.*?)\}#', $this->_tpl_data['file_contents'], $matches);
        foreach( $matches[1] as $found )
        {
            if( $key == $found )
            {
                str_replace($matches[0][0], $data, $this->_tpl_data['file_contents']);
            }
        }
with

Code: Select all

preg_match_all('#\{(.*?)\}#', $this->_tpl_data['file_contents'], $matches);
        foreach( $matches[1] as $found )
        {
            if( $key == $found )
            {
               $this->_tpl_data['file_contents'] =  str_replace($matches[0][0], $data, $this->_tpl_data['file_contents']);
            }
        }
and any reason to do the preg_match_all?
why not str_replace("\{$key\}", $data,$template)
if the key doesnt exist, no changes will be made

Posted: Mon Nov 14, 2005 7:57 pm
by Sphenn
Thanks Jshpro2, this solved it.

Thanks again :D

Sphenn