Jump to content

Including File in the Middle of text


maxudaskin

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-

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.