Welcome Guest, Not a member yet? Register   Sign In
How to execute php in string?
#1

[eluser]rogierb[/eluser]
Hi all,

I think my brain froze since I'm unable to get a decent solution to this problem...

Problem:
Somehow I'm stuck with a very large string which holds PHP code:

Code:
$string = "a lot of text <php if($blah ==$blah$blah) { echo $dosomething} ?&gt; an yet another text"

echo $string // does not work, go figure

How do I execute the code within the string?

I even tried:
Code:
ob_start();
echo $string ;
contents = ob_get_contents();
ob_end_clean();
          
return $contents;

Even tried putting my head in the oven, still no luck...

So anyone...help...
#2

[eluser]xwero[/eluser]
Code:
$dosomethingoutput = '';
if($blah ==$blah$blah) { $dosomethingoutput = $dosomething; }
echo 'a lot of text '.$dosomethingoutput.' an yet another text';
#3

[eluser]Pascal Kriete[/eluser]
Code:
$string = "a lot of text <WHEREISTHEQUESTIONMARKphp if($blah ==$blah$blah) { echo $dosomething} ?&gt; an yet another text"

echo $string // does not work, go figure

Maybe it's just a typo, but you're missing a question mark.
#4

[eluser]rogierb[/eluser]
That would only work if I knew what the PHP code would be.

I don't. Maybe I should have mentioned that;-)

And the string can be several pages long, hold multiple codeblocks etc.
#5

[eluser]Pascal Kriete[/eluser]
So where is the code coming from?

EDIT: I think you might be looking for eval.
#6

[eluser]rogierb[/eluser]
The syntax is okay; I saved the string a couple of times as an php file en tested it. No problem there.

The PHP is generated by another script based on info in a DB.

It just might be the solution we chose that's not working, but still would like to know how to execute PHP within a string
#7

[eluser]rogierb[/eluser]
Hmm, I already tried eval(). And it should work, but it doesn't. So I think I'm either missing something or I need a vacation.
#8

[eluser]Craig A Rodway[/eluser]
The string of code passed to eval() must be just PHP code - no PHP tags and no plain-text.

If you have control over the string and it must contain some non-PHP sections, I'd recomment using your own delimeters to denote the PHP section and using some string functions to extract it and run that through eval().
#9

[eluser]rogierb[/eluser]
Well, I think finally found it.

Code:
$string = "I am an &lt;?php echo 'idiot'; ?&gt;";

echo eval ($string);
did not work.

But after some random typing and testing (with forehead ramming keyboard)

Code:
$string = "I am an &lt;?php echo 'not that big an idiot'; ?&gt;";

echo eval ("?&gt;".$string);

Did the trick.

Thanx y'all!
#10

[eluser]sandwormusmc[/eluser]
So you had to put two ?&gt;'s at the end of the string? Looks a bit odd ... but hey, if it works ...




Theme © iAndrew 2016 - Forum software by © MyBB