开发者

PHP Dynamic Regexp replacement

开发者 https://www.devze.com 2023-03-30 18:46 出处:网络
I would like to know if there is a way to bind PHP function inside a regexp. Example: $path_str = \'/basket.php?nocache={rand(0,10000)}\';

I would like to know if there is a way to bind PHP function inside a regexp.

Example:

$path_str = '/basket.php?nocache={rand(0,10000)}';
$pattern = ? // something i have no idea
$replacement = ? // something i have no idea

$path = preg_replace($pattern, $replacement, $path开发者_高级运维_str);

Then :

echo "'$path'";

would produce something like

'/basket.php?nocache=123'

A expression not limited to the 'rand' function would be even more appreciated.

Thanks


You could do the following. Strip out the stuff in between the {} and then run an eval on it and set it to a variable. Then use the new variable. Ex:

$str = "/basket.php?nocache={rand(0,10000)}";
$thing = "rand(0,10000)";
eval("\$test = $thing;");
echo $test;

$thing would be what's in the {} which a simple substr can give you. $test the becomes the value of executing $thing. When you echo test, you get a random number.


Don't, whatever you do, store PHP logic in a string. You'll end up having to use eval(), and if your server doesn't shoot you for it, your colleagues will.

Anywhoo, down to business.

Your case is rather simple, where you need to append a value to the end of a string. Something like this would be sufficient

$stored = '/basket.php?nocache=';
$path   = $stored . rand(0,10000);

If, however, you need to place a value somewhere in the middle of a string, or possibly in a variable location, you could have a look at sprintf()

$stored = '/basket.php?nocache=%d&foo=bar';
$path   = sprintf($stored, rand(0,10000));


I would not try to store functions in a database. Rather store some kind of field that represents the type of function to use for each particular case.

Then inside your crontab you can do something like:

switch ($function)
{
    case 'rand':
    $path_str = '/basket.php?nocache='. rand(0,10000);
}

e.t.c

0

精彩评论

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