PHP 动态正则表达式替换
我想知道是否有一种方法可以在正则表达式中绑定 PHP 函数。
示例:
$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);
然后 :
echo "'$path'";
会产生类似
'/basket.php?nocache=123'
不限于“rand”函数的表达式将更受赞赏。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行以下操作。去掉 {} 之间的内容,然后对其运行 eval 并将其设置为变量。然后使用新变量。例如:
$thing 就是一个简单的 substr 可以给你的 {} 中的内容。 $test 成为执行 $thing 的值。当您回显测试时,您会得到一个随机数。
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:
$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.
无论您做什么,都不要将 PHP 逻辑存储在字符串中。您最终将不得不使用
eval()
,并且如果您的服务器不向您开枪,您的同事也会这样做。无论如何,言归正传。
您的情况相当简单,您需要将一个值附加到字符串的末尾。这样的东西就足够了
,但是如果您需要在字符串中间的某个位置或者可能在变量位置放置一个值,您可以看看
sprintf()
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
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()
我不会尝试将函数存储在数据库中。而是存储某种表示用于每种特定情况的函数类型的字段。
然后在你的 crontab 中你可以做类似的事情:
等等
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:
e.t.c