SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist ucahg's Avatar
    Join Date
    Apr 2001
    Location
    Sarnia, Ontario, Canada
    Posts
    434
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation Using PHP Code Inside a Regular Expresion

    How would I add the functionality to a PHP script so if it is parsing text and comes across this:

    ...other text...
    [PHP]
    echo 'Hello World';
    [/PHP]
    ...othertext...

    that it will show up as

    ...other text...
    Hello World
    ... other text ...

    So that the PHP code is executed. How would I do this? I'm quite sure it is possible, because I execute code in my regexps all the time, but I'm not quite sure how to do this.

    (Please answer with preg_replace, not ereg, thanks)
    Love it? Hate it? Helpful? Useless?
    Use the rate button to let me know what you think of my post!

  2. #2
    SitePoint Wizard silver trophy redemption's Avatar
    Join Date
    Sep 2001
    Location
    Singapore
    Posts
    5,269
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can use eval()... as for extracting the code, i can't help cos i'm not good at regexp, esp. not PCRE

  3. #3
    Making a better wheel silver trophy DR_LaRRY_PEpPeR's Avatar
    Join Date
    Jul 2001
    Location
    Missouri
    Posts
    3,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    be VERY VERY careful using eval()! if it's your code, fine. but don't trust what the user enters. that said, try this:

    Code:
    $txt = preg_replace('#\[ php](.+?)\[/php]#eis', 'eval_stuff("$1")', $txt);
    
    
    function eval_stuff($txt)
    {
    	// This fixes any single quotes that get
    	// messed up being passed to this function
    	$txt = str_replace("\'", "'", $txt);
    
    	ob_start();
    	eval($txt);
    	$output = ob_get_contents();
    	ob_end_clean();
    
    	return $output;
    }
    if your version of PHP is less than 4.0.4, replace $1 with \1. BTW, the ob_xxx stuff makes any echo 'blah'; code's output be returned rather than echo'ed right at that point.
    - Matt ** Ignore old signature for now... **
    Dr.BB - Highly optimized to be 2-3x faster than the "Big 3."
    "Do not enclose numeric values in quotes -- that is very non-standard and will only work on MySQL." - MattR


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •