#native_company# #native_desc#
#native_cta#

Dynamic PHP

By Alan Langridge
on January 31, 2001

Version: 1

Type: Function

Category: Databases

License: GNU General Public License

Description: I searched for a day to find an example of running some PHP that is embedded in the middle of a string that was read from a database. I couldn’t find anything, so I wrote this instead!

What it does is find any occurances of <?php blah; ?> in a string, pull out the php code, run it and shove the result of the php back in the string.

Restrictions on usage (tech not legal!) are:

. The php must be a single function call;
. The function must return its output, not print it.

For example, I’ve used it on a dynamic web site that’s essentially text article based. The articles are in a database and sometimes the writers need to link to other articles.

Originally, they just hand wrote the <A> links, but that lost the context variables when the users followed the links (the site doesn’t use cookies). Now the authors use “<?php link_article(article_id, “channel name”, “link text”); ?>” instead, and the context variables are passed on the links.

function pre_process_body($arg_body)
{
   while(eregi('(.+)<?php (.+) ?>(.+)', $arg_body, $arr_body))
   {
      $php = '$tmp = '.$arr_body[2];

      if(substr($php,-1,1) != ';')
      {
         $php .= ';';
      }
      eval($php);
      $arg_body = $arr_body[1].$tmp.$arr_body[3];
   }
   return($arg_body);
}


function link_article($arg_art_id, $arg_chan, $arg_linktext)
{
   $ret  = '<A HREF="'.$arg_chan.'/topic.php3';
   $ret .= context_vars();
   $ret .= 'art_id='.rawurlencode($arg_art_id);
   $ret .= '">';
   $ret .= $arg_linktext.'</A>';

   return($ret);
}