Reputation: 473
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
[{CONTENT:meta}]
[{CONTENT:title}]
[{CONTENT:head}]
</head>
[{CONTENT:open_body}]
<p>[{LOCATION:main_1}]</p>
<p>[{LOCATION:main_1}]</p>
</body>
</html>
I have the above "template_file"
in a $string
. I am trying to do a loop that cycle through the string and on each iteration gives me the left side of the tag, the tag itself in a new variable, and then the right side in another string. I can't use str_replace
here because I need to extract what's inside of the tags before replacing them.
The output would be something like:
$string_left = everything up to a "[{"
$command = "CONTENT:meta"
$string_right= everything after the "}]".
I would then process data using the CONTENT:meta
and then put the thing back together (string_left + new data + string_right)
and then keep doing it until the entire thing was parsed.
Upvotes: 0
Views: 78
Reputation: 70721
You can use preg_replace
with a regex that matches [{...}]
, along with a replacer function that takes the matched "command" and returns a suitable replacement string:
$output = preg_replace('/\[{([^}]*)}\]/e', 'my_replacer(\'$1\')', $string);
And define my_replacer
as follows:
function my_replacer($command) {
...
return $replacement;
}
Upvotes: 1
Reputation: 10091
Why don't you just use a template software instead? Here's a big list.
http://www.webresourcesdepot.com/19-promising-php-template-engines/
Upvotes: 0
Reputation: 1357
You can do this with a relatively simple regular expression:
$inputString = "left part of string [{inner command}] right part of string";
$leftDelim = "\[\{";
$rightDelim = "\}\]";
preg_match("%(.*?)$leftDelim(.*?)$rightDelim(.*)%is", $inputString, $matches);
print_r($matches);
This will demonstrate how to use the regular expression. The extra slashes in the delim variables are because your delimiters use regex characters, so you need to escape them.
Upvotes: 2