Jump to content

[SOLVED] calling a function in the middle of non-php code block


Recommended Posts

Hello, I am trying to write a function that reads a block of HTML. There are certain cues in the HTML that the function will replace with certain things (like a template).

 

So far I've got that down, but I have a problem. There's a keyword that I want to replace with the call to a function, instead of just a variable. So like, for example, if the keyword was "apple", and I had the HTML code block

 

I really would like an apple right now.

 

then PHP would print out "I really would like an ", and then call the function I want it to call, and then print out " right now."

 

I could do a str_replace() to replace the keyword ("apple") with the function call, and then just do an eval() on the whole block, but I don't want the block to be able to execute PHP code of its own.

 

Any hints as to how I might go about this? Any help is appreciated.

Any hints as to how I might go about this? Any help is appreciated.

 

Really depends on how your parser works already. It could be as simple as....

 

<?php

  function foo() {
    return "banana";
  }

  $s = "I really would like an apple right now.\n";

  echo str_replace('apple', foo(), $s);

?>

Oh wow, I had no idea you could call a function inside a str_replace(). Thanks a bunch! One question though, in your example, let's say you were to change it to

 

<?php

  function foo() {
    return "banana";
  }

  $s = "I really would like an apple right now.\n";

  $code = str_replace('apple', foo(), $s);

  /* some other code */

  echo $code;

?>

 

Would foo() get called during the str_replace, or not until $code gets echoed? I need it to not be called until the code is printed out.

Well, we're going to have to move from example code to your real code to figure that one out, because as it stands right now in the example code, the echo is already happening right after the whole str_replace/foo() thing.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.