Character Replacement script

Hey,

currently working on a project where I am putting text into a template.

I have a working example below
http://adamhuxtable.com/dt/Templates/barratt_generic_notools.php

What I would like is to add a script that replaces characters ie I would like it to replace ^ with ^ so that it is hard coded.

I have to scripts running to output the final product

<?php
	require_once ( 'DreamweaverTemplate.php' );
	
	$thefile = "demo.html";
	
	$parsed = new DreamweaverTemplate ( $thefile );
	
	if ( ! count ( $_POST ) )
		{
						
		?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
		"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<title>Template Generator - Barratt Generic, No Tools</title>
        <script type="text/javascript">
function select_text()
{
var content=eval("document.myform.editable_$region");
content.focus();
content.select();
}
</script>
	</head>
	<body>
		<div style="font-family:Arial, Helvetica, sans-serif; background:url(../assets/bg.gif) repeat;">
 <div style="margin:0 auto; text-align:center;">
<a href="http://www.splashworldwide.com" target="_blank"><img src="http://www.sitepoint.com/forums/assets/logo.png" alt="" width="500" height="114" border="0" /></a>
</div>
<?php
			$regions = $parsed->GetEditableRegions();
			
			if ( count ( $regions ) )
				{
				?>
<form name="myform" action="barratt_generic_notools.php" method="post">
					<table cellpadding="3" cellspacing="0" width="500" style="margin:0 auto;">
						<?php
						foreach ( $regions as $region )
							{
							echo "<tr>\
";
								
								echo "<td width='600' valign='top' style='color:#ffffff;'><label for='editable_$region'>$region".":</label><br><textarea style='border:#4f91cd solid 2px; font-family:Arial, Helvetica, sans-serif; color:#4f91cd; width:500px;' onClick='select_text()' id='editable_$region' name='editable_$region' cols='60' rows='3'>";
								echo htmlentities ( $parsed->GetEditableData ( $region ) );
								echo "</textarea></td>\
";
							echo "</tr>\
";
													// The text string 
			$text = $reigon; 
			
			// The word we want to replace 
			$oldWord = "^"; 
			
			// The new word we want in place of the old one 
			$newWord = "blue"; 
			
			// Run through the text and replaces all occurrences of $oldText 
			$text = str_replace($oldWord , $newWord , $text);
							}
	 
						?>
						<tr><td style='text-align:center' colspan='2'><input type='submit' value='Submit' style="background:#4f91cd; color:#ffffff; width:150px; height:40px; margin:30px 0 50px 0;-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; border:#FFF 2px solid;" /></td></tr>
					</table>
				</form>
				<?php
				}
			else
				{
				if ( !file_exists ( $thefile  ) )
					{
					?><h1>FILE NOT FOUND</h1><?php
					}
				else
					{
					?><h1>NO EDITABLE REGIONS</h1><?php
					}
				}
		?>
		</div>
	</body>
</html>
		<?php
		}
	else
		{
		$regions = $parsed->GetEditableRegions();
		
		while ( list ( $key, $value ) = each ( $_POST ) )
			{
			$value = stripslashes ( $value );
			if ( preg_match ( "/editable_/", $key ) )
				{
				$keyname = preg_replace ( "/editable_/", "", $key );
				$parsed->SetEditableData ( $keyname, $value );
				}
			}
			
			





		
		$code = $parsed->GetFileData();
		
		/*	SECURITY RISK!
			I won't enable this in my demo, because it allows people to execute server code on my server.
			Enable it if you want to try putting PHP into the editable regions.

		$code = str_replace ( '<'.'?php', '<'.'?', $code );
		$code = '?'.'>'.trim ( $code ).'<'.'?';
		
		$code = eval ( $code );
		*/
		
		print $code;
		}
?>

<?php
/*
	DREAMWEAVER TEMPLATE PARSER
	
	This class will read a Dreamweaver template file, and break it into "sections."
	The sections will be placed into an associative array.
	
	This was written in order for me to use Dreamwever templates in CMS systems
	like WordPress and Gallery. This allows me to have a blank template file sitting
	in an appropriate place, and I can grab it and parse it in order to shoehorn the
	CMS data into it, which gives me the full advantage of the Dreamweaver template
	system.
	
	It can be used either by accessing the template in "chunks," or by loading the
	template up with data, then displaying the entire file.
	
	KNOWN ISSUE: Don't declare multiple editable regions on the same line.
	
	Version: 1.0.1 (Added that caveat above)
	Date Mod: September 21st, 2005
	Author: Chris Marshall (cmarshall@xemaps.com)
	
	Version: 1.0
	Date Mod: September 20th, 2005
	Author: Chris Marshall (cmarshall@xemaps.com)
	
	License:
		Take me, You Gypsy Stallion.
		Open Source.
		No guarantees, no claims of ownership, but don't try to copyright this.
		
	Origination: http://www.cmarshall.net/DreamweaverTemplate
*/

class DreamweaverTemplate
{
	/*
	* ****************************************
	*                 Members
	* ****************************************
	*/
	
	/**
	* This contains a POSIX path to the file to be parsed.
	*
	* @var object DreamweaverTemplate $_file_to_parse
	* @access private
	*/
	var $_file_to_parse;

	/**
	* This contains the parsed file as an associative array.
	*
	* @var object DreamweaverTemplate $_parsed_file
	* @access private
	*/
	var $_parsed_file;

	/*
	* ****************************************
	*                 Methods
	* ****************************************
	*/
	
	/**
	* Constructor
	* @param string a POSIX path to the file to be parsed
	* @access public
	*/
	function DreamweaverTemplate ( $in_file_to_parse )
		{
		assert ( '!empty($in_file_to_parse)' );
		$this->_file_to_parse = $in_file_to_parse;
		$this->_ParseFile();
		}
	
	/**
	* Parse the file
	* @access private
	*/
	function _ParseFile()
		{
		$this->_parsed_file = "";	// Make sure we are empty.
		// Read in the file
		$template_file = file_get_contents ( $this->_file_to_parse );
		$template_file = preg_split ( '/<!-- .*?BeginEditable [^"]*"|<!-- .*?EndEditable -->/',  $template_file );
		if ( count ( $template_file ) )
			{
			$index = 0;
			foreach ( $template_file as $section )
				{
				$key = "";
				$value = "";
				list ( $key, $value ) = preg_split ( '/-->/', $section );

				if ( !preg_match ( '/^[^"]*?" /', $key ) )
					{
					$key = $section;
					$value = "";
					}
				
				if ( !$value && !preg_match ( '/^[^"]*?" /', $key ) )
					{
					$value = $key;
					$key = "locked_$index";
					$index++;
					}
				else
					{
					$key = str_replace ( '" ', '', $key );
					$key = "editable_$key";
					}
				
				$this->_parsed_file[$key] = $value;
				}
			}
		}
	
	/**
	* Return the file from the end of one editable region to another
	* All data in all editable regions will be returned, with the exception of the destination region.
	* That data will only be returned if the $in_include_data is true.
	* $in_from and $in_to must be editable regions.
	* The "locked_" and "editable_" prefixes are not to be passed in.
	* This may seem counter-intuitive, as you send in the destination before the source, but this makes
	* the function easier to use.
	* @param string the editable region you want to stop at (blank is the end of the file)
	* @param string the editable region that you wish to start at (blank is the beginning of the file)
	* @param bool nonzero if you want to include the data already in the destination editable region
	* @access public
	*/
	function GetFileData ( $in_to = "", $in_from = "", $in_include_data = false )
		{
		$ret = "";
		$start_reading = false;
		
		if ( !$in_from )
			{
			$start_reading = true;
			}
		else
			{
			$in_from = "editable_$in_from";
			}
		
		if ( $in_to )
			{
			$in_to = "editable_$in_to";
			}
		
		if ( count ( $this->_parsed_file ) )
			{
			reset ( $this->_parsed_file );
			while ( list ( $key, $value ) = each ( $this->_parsed_file ) )
				{
				if ( !$start_reading && ($key == $in_from) )
					{
					$start_reading = true;
					continue;
					}
				
				if ( $start_reading )
					{
					if ( ($key == $in_to) && !$in_include_data )
						{
						break;
						}
					
					$ret .= $value;

					if ( $key == $in_to )
						{
						break;
						}
					}
				}
			}
		
		return $ret;
		}
	
	/**
	* Returns an array with the editable region names (without the "editable_" prefix)
	* @access public
	*/
	function GetEditableRegions()
		{
		$ret = array();
		if ( count ( $this->_parsed_file ) )
			{
			reset ( $this->_parsed_file );
			while ( list ( $key, $value ) = each ( $this->_parsed_file ) )
				{
				if ( preg_match ( "/editable_/", $key ) )
					{
					array_push ( $ret, preg_replace ( "/editable_/", "", $key ) );
					}
				}
			}
		
		return $ret;
		}
	
	/**
	* Returns a copy of the actual array
	* @access public
	*/
	function GetParsedArray()
		{
		return $this->_parsed_file;
		}
	
	/**
	* Returns the data within an editable region
	* @param string the editable region you want to see (must be valid, and does not include the "editable_" prefix)
	* @access public
	*/
	function GetEditableData ( $in_editable_region )
		{
		assert ( '!empty($in_editable_region)' );
		return $this->_parsed_file["editable_$in_editable_region"];
		}
	
	/**
	* Sets data into an editable region
	* Remember that, when accessing this, you need to specify the $in_include_data flag.
	* @param string the editable region you want to edit (must be valid, and does not include the "editable_" prefix)
	* @param string the data you want to place in that region (can be empty)
	* @access public
	*/
	function SetEditableData ( $in_editable_region, $in_data = "" )
		{
		assert ( '!empty($in_editable_region)' );
		
		$this->_parsed_file["editable_$in_editable_region"] = $in_data;
		}
};
?>

I have tried adding this code within the first script in several places but no luck.

<?php 

// The text string 
$text = "$reigons"; 

// The word we want to replace 
$oldWord = "brown"; 

// The new word we want in place of the old one 
$newWord = "blue"; 

// Run through the text and replaces all occurrences of $oldText 
$text = str_replace($oldWord , $newWord , $text); 

// Display the new text 
echo $text; 

?>

I know the basics of how PHP work but it defiantly isn’t my speciality. :wink:

Thanks in advance
Adam

Well its just outputting text from a form in to a template which seems to be working fine baring a few minor hiccups.

But I would like it once its running the script to put the text within the template for it to check if there are any characters that need encoding ie ^ with the hard code, and others like the dagger symbol.

As I ain’t great at PHP I thought this script was pretty good :frowning:

Barring all that editable_ nonsense, what exactly are you after? That ‘template’ library looks awful.

Okay. :slight_smile:

Let’s take this simple Template object.

template.php


class Template
{
  protected
    $file = null,
    $data = array();

  public function __construct($file){
    if( ! is_readable($file)){
      throw new Exception('Template file is unreadable');
    }
    $this->file = $file;
  }
  
  public function bind($key, $value){
    $this->data[$key] = $value;
    return $this;
  }
  
  public function render(){
    ob_start();
    extract($this->data);
    include $this->file;
    $__ = ob_get_contents();
    ob_end_clean();
    return $__;
  }
  
  public function __toString(){
    return $this->render();
  }
}

… and this template

demo.tpl


<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <h1>Hello, <?php echo $name; ?></h1>
  </body>
</html>

You can then, create a simple templated page like this


require_once 'template.php';
$view = new Template('demo.tpl');
$view->bind('title', 'Sitepoint Demo');
$view->bind('name', 'Adam');
echo $view;

/*
  <html> 
    <head> 
      <title>Sitepoint Demo</title> 
    </head> 
    <body> 
      <h1>Hello, Adam</h1> 
    </body> 
  </html>
*/

Can you see how we replace the value of $title and $name in the template (.tpl) ?

Thank you Anthony, I shall give that a play when I get back from my lunch!

Appreciate your help :smiley: Shall let you know how I get on!

I have built template.php and demo.tpl, (this might be a stupid question but where do I go from here?) Where would I put in the new content (where would I create the form and how would I bind it?) because I noticed you are binding data here


$view->bind('title', 'Sitepoint Demo');
$view->bind('name', 'Adam');

Sorry for the novice questions once I have the basic structure there I will be able to get the rest done. Just struggling to get to grips with building this type of system.

No problem.

Okay, let take this piece of code.


if('POST' === $_SERVER['REQUEST_METHOD']
{
  $view = new Template('demo.tpl');
  $view->bind('title', $_POST['title']);
  $view->bind('name', $_POST['name']);
}
else
{
  $view = new Template('form.tpl');
}

echo $view;

This will check if we have a form submission, if so it will load the template (demo.tpl), bind the submitted data and output it. If not, it will load the form template (form.tpl) and output that? Can you see how that works?

The form.tpl just contains:


<html> 
  <head> 
    <title>Sitepoint Demo - Form</title> 
  </head> 
  <body>
    <form action="#" method="post">
      <p>Title: <input name="title" type="text" /></p>
      <p>Name: <input name="name" type="text" /></p>
      <input type="submit" value="generate" />
  </body> 
</html>

So files wise, you now have index.php (the script above), demo.tpl and form.tpl.

Um righty I get how the code is working, however bit confused in which file each bit of code goes in to, I have three file:

demo.tpl

<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <h1>Hello, <?php echo $name; ?></h1>
  </body>
</html>

form.tpl



<html> 
  <head> 
    <title>Sitepoint Demo - Form</title> 
  </head> 
  <body>
    <form action="#" method="post">
      <p>Title: <input name="title" type="text" /></p>
      <p>Name: <input name="name" type="text" /></p>
      <input type="submit" value="generate" />
  </body> 
</html>

template.php



<?php 
if('POST' === $_SERVER['REQUEST_METHOD']
{
  $view = new Template('demo.tpl');
  $view->bind('title', $_POST['title']);
  $view->bind('name', $_POST['name']);
}
else
{
  $view = new Template('form.tpl');
} 



class Template
{
  protected
    $file = null,
    $data = array();

  public function __construct($file){
    if( ! is_readable($file)){
      throw new Exception('Template file is unreadable');
    }
    $this->file = $file;
  }
  
  public function bind($key, $value){
    $this->data[$key] = $value;
    return $this;
  }
  
  public function render(){
    ob_start();
    extract($this->data);
    include $this->file;
    $__ = ob_get_contents();
    ob_end_clean();
    return $__;
  }
  
  public function __toString(){
    return $this->render();
  }
}  

?>

Feel like I’m being a pain in the ass now :stuck_out_tongue:

You are. :lol:

Here’s how I would lay the files out.

/index.php
/lib/template.php
/views/form.tpl
/views/demo.tpl

And the contents of these files would be…

index.php


<?php
error_reporting(-1);
ini_set('display_errors', true);

require_once 'lib/template.php';

if('POST' === $_SERVER['REQUEST_METHOD']
{
  $view = new Template('views/demo.tpl');
  $view->bind('title', $_POST['title']);
  $view->bind('name', $_POST['name']);
}
else
{
  $view = new Template('views/form.tpl');
}

echo $view;

template.php


<?php
class Template
{
  protected
    $file = null,
    $data = array();

  public function __construct($file){
    if( ! is_readable($file)){
      throw new Exception('Template file is unreadable');
    }
    $this->file = $file;
  }
  
  public function bind($key, $value){
    $this->data[$key] = $value;
    return $this;
  }
  
  public function render(){
    ob_start();
    extract($this->data);
    include $this->file;
    $__ = ob_get_contents();
    ob_end_clean();
    return $__;
  }
  
  public function __toString(){
    return $this->render();
  }
}

form.tpl


<html> 
  <head> 
    <title>Sitepoint Demo - Form</title> 
  </head> 
  <body>
    <form action="#" method="post">
      <p>Title: <input name="title" type="text" /></p>
      <p>Name: <input name="name" type="text" /></p>
      <input type="submit" value="generate" />
  </body> 
</html>

demo.tpl


<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <h1>Hello, <?php echo $name; ?></h1>
  </body>
</html>

That should put you on the right track. :wink:

Righty I’m half on the right track now have the files all setup in the correct folders etc however there is an error popping up stating that there is an unexpected ; on line9 - $view = new Template(‘views/demo.tpl’);

can’t see why this error would come up…

Ah, my bad. A small typo.


<?php
error_reporting(-1);
ini_set('display_errors', true);

require_once 'lib/template.php';

if('POST' === $_SERVER['REQUEST_METHOD'])
{
  $view = new Template('views/demo.tpl');
  $view->bind('title', $_POST['title']);
  $view->bind('name', $_POST['name']);
}
else
{
  $view = new Template('views/form.tpl');
}

echo $view;

GREAT!! Thats fantastic and just what I needed to get me started! Hopefully I can pull the rest together pretty quickly now!

Thank you for all your help and patience!! :slight_smile:

Hey, no worries.

Feel free to pester as often as you like. :wink:

Anthony.