Miles
Miles

Reputation: 1

PHP dom replacement

I have been looking for some time now and haven't been able to come up with anything. I have a page that contains both html and php.

<div>%%replace_me%%</div>


<? replaceStr("replace_me", "foobar"); ?>

I need a function that would change the above %% string into foobar to make the html look like this:

<div>foobar</div>

The text will Always be surrounded by percentage signs but not always enclosed in a div. There will be php on the page as well as the %% vars, so storing the page in a $var and str replacing hasn't worked for me.

Upvotes: 0

Views: 119

Answers (2)

Michael Mior
Michael Mior

Reputation: 28752

You'll have to add ob_start() near the beginning of your page to ensure that output is buffered and not sent to the user until you've had a chance to parse it. I would then try to collect all calls to replaceStr() until all possible %% tags have been output and you're ready to replace them all in one shot. Then, this should do the trick:

function replace_str(&$body, $tag, $replace) {
   str_replace('%%'.$tag.'%%', $replace, $body);
}
$body = ob_get_clean();
replaceStr($body, 'replace_me', 'foobar');
// other calls to replaceStr...
echo $body
ob_end_flush();

Upvotes: 1

David
David

Reputation: 218827

It sounds like you're looking for a template engine. Smarty is a popular one for PHP. There are others as well.

Understand that within the context of the server-side code (PHP) there is no "DOM" or even really "HTML" in the sense that you're implying. There's HTML in the .php file, but you can't really interact with it like that. It's just text in the file waiting to be served down to the client after the PHP engine interprets the PHP code.

DOM parsing and all that stuff happens in the browser once the content is delivered to the client, which is after the server-side code has run. There are PHP DOM parsers as well, but they're for consuming HTML and manipulating it within the PHP code, not for interacting with the HTML markup that's outside of the PHP code in the same .php file.

Upvotes: 1

Related Questions