Jump to content

Problem With Preg Replace


zachary

Recommended Posts

Hi,My goal is to make a template system that will display contents when called from a {{template:TEMPNAMEHERE}}...

	$content = nl2br(file_get_contents($location));	function include_template($name) {		return file_get_contents("help-docs/template/" . $name . ".hlp");	}	echo preg_replace("\{\{template:(.*?)\}\}", include_template($1), $content);

The problem is that I am trying to pass along the $1 variable to a function but there is no way I could do that and I have tried everything, the function basically pulls up the template file and returns it...

Link to comment
Share on other sites

$1 is not a variable, it won't work in that function. include_template() is run before the regular expression is evaluated.What you should do is find every instance of the expression, remember its position and length (maybe by storing it in an array), then you delete each one and write the replacement into the string.This will require several different string functions, and there are probably many other techniques you could use, but they'll require more code than just preg_replace().

Link to comment
Share on other sites

I know it was incorrect code, but I was trying to show you what I am trying to achieve. I don't have the knowledge to pull off something like that... can someone devise an easier approach? This is built for a help system so it would be getting some serious traffic.

Link to comment
Share on other sites

I know it was incorrect code, but I was trying to show you what I am trying to achieve. I don't have the knowledge to pull off something like that... can someone devise an easier approach? This is built for a help system so it would be getting some serious traffic.

Link to comment
Share on other sites

If you're creating a template system you can't really get around manually parsing the template, it's not really an easy thing to do either. The template system I made is somewhere around 50kb of code to parse and process the template, although it does more than regular find-and-replace (and probably isn't as efficient as it could be). But there's not really a way to get around it, you need to search for the next instance of whatever starts a template tag, then search from there until you find the ending part, and then you have the entire tag. You would break up the tag to get the different parts of it (name, value, whatever), and process it how you want, then replace the tag in the source with the processed text and start parsing from the beginning of where the tag was again. It gets really fun when you can nest template tags and need to keep track of how many levels you've nested in order to find the correct ending tag.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...