...

View Full Version : Fastest way for a string replace in document



TheBuggerGuy
01-17-2004, 01:45 AM
Lets say that in your document you typed $theme and you wished that text to be replaced with a word of your choice via PHP. What would be the easiest way without having to put your HTML in the <?php ?> tags?

Example:

<?php

script (or link to external script)

?>

<html>
<body>
My new theme today is called $theme. I hope you like $theme!
</body>
</html>


Thanks

Mhtml
01-17-2004, 02:23 AM
Load the file and echo it out. That's the way I do my website ...

Pretty simple really ...


function LoadTemplate($strFile) {
if( !file_exists ( $strFile ) )
die("File '$strFile' does not exist or access permissions disallow access!");
$handle = fopen ( $strFile, "r" );
return fread( $handle, filesize( $strFile ) );
}


That function returns the content of the file and checks to make sure it's there first ....

Then just do something like --


$page = LoadTemplate("your_file.htm");
echo str_replace("\$theme",$theme,$page);


[edit:] A few syntax modifications

TheBuggerGuy
01-17-2004, 02:33 AM
ok, lets say that you wanted to expand and put several strings to be replaced over many documents. is there a way without putting the filename in the script?

Mhtml
01-17-2004, 02:38 AM
Hrmm .. well that makes it more complex, especially if you want to do it over many pages without putting the filename in the file ...The best way would be to use basically the same method ...

If you were to use regexp you could just search for anything not in <?php ?> delimeters that matches the variable you want to replace and replace it ... would this be acceptable?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum