Jump to content

Recommended Posts

I have the following code taken from a class I am writing to take text from a database, find a code tag ([ code ] and [ / code ]) and run the code inside, outputting the result, with everything in the same order.

 

Class code (partial)

function runCode($code, $body)
{
	trim($code);

	$function = explode(' ', $code);
	$type     = $function[0];

	if($type == 'include') {
		if(!file_exists($_SERVER{'DOCUMENT_ROOT'} . '/include/' . $function[1])) {
			header('Location: index.php?p=error&iss=001&ref=' . $_GET['p'] . '&ref=' . $_GET['ref']);
		}
		else {
			if($body) {
				include 'include/' . $function[1];
			}
		}
	}
}

function parseInlineCode($string = NULL, $body = false)
{
	$regex = "%(\[code\])(.*)(\[/code\])%";
	preg_match($regex, $string, $code);
	$code  = explode(";", $code[2]);

	for($i = 0; $i < count($code); $i++) {
		$this->runCode($code[$i], $body);
	}
}

 

For example, if I had:

Some text. [ code ]include 'test.php'; run main;[ / code ]
Yellow banana...

with test.php being

<?php
function main()
{
    echo 'foobar';
}
?>

How could I get it to output:

Some text. foobar

Yellow banana...

 

Right now, I have it outputting like this:

foobarSome text.

Yellow banana...

 

--

 

Thank you in advance for you time

Link to comment
https://forums.phpfreaks.com/topic/200238-including-file-in-the-middle-of-text/
Share on other sites

Apart from being the worst thing to do if it's not properly protected - you can use eval() to execute code that you can pull using this function:

preg_match_all("/\[code\](.+)\[\/code\]/i",$text,$matches);

 

$text should be the text file in a single string.

$matches will hold all the matches, and other data from the regular expression. (use print_r($matches) to see what it has caught).

 

-cb-

 

The function puts any and all matches from the pattern into the $matches array.

 

Since we only used one set of parenthesis () - We only have to go to: $matches[1]- to get all the matches from that parenthesis.

 

So $matches[1]  should hold all the code you wanted to pull.

 

(To print an array, use Print_r($array); - var_dump() is useful if you want to confirm string sizes or data types.)

 

-cb-

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.