开发者

How to fix PHP preg_replace() faulty result order?

开发者 https://www.devze.com 2023-03-20 17:06 出处:网络
The faulty result I get now is: 17th of July, 2011Today 开发者_运维知识库is . function finclude($file){

The faulty result I get now is: 17th of July, 2011Today 开发者_运维知识库is .

function finclude($file){
    include($file);
}
$str = "Today is {include 'date.php'}.";
echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str);

date.php :

<?php echo date('jS \of F'); ?>, 2011

Expected result: Today is 17th of July.


function finclude($file){
    return include($file);
}

<?php return date('jS \of F'); ?>

Result isn't expected because You print date, then finclude return null, then you print "Today is "+finclude


What you call faulty in your result order is actually caused by the execution order of your statements:

echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str);

Will start the output (echo) and then call the preg_replace function. In which you make use of the e - eval modifier to execute code, namely the function finclude.

So finclude get's executed earlier than preg_replace will return it's result.

So if finclude does output on its own, it will be displayed in front of the result of preg_replace.

Knowing this is half the solution to your problem. It's much likely you didn't intend this output order (your expected result differs) and you just wanted to make finclude return a value instead of outputting something. To convert output into a return value you can make use of an output buffer:

function finclude($file){
    ob_start();
    include($file);
    return ob_get_clean();
}
$str = "Today is {include 'date.php'}.";
echo preg_replace("/\{include '(.*)\'}/e", 'finclude("$1")', $str);

This will ensure that every output within finclude will be returned as a return value instead.

That done you can re-use existing code/includes that normally outputs within your search and replace operation. However using the e modifier always is dangerous and it normally should be prevented. So take care.


i think you need to put <?php return date('jS \of F'); ?> in date.php

0

精彩评论

暂无评论...
验证码 换一张
取 消