gpt4 book ai didi

php - 用表达式中的一项替换花括号表达式

转载 作者:行者123 更新时间:2023-12-03 23:43:19 24 4
gpt4 key购买 nike

这是一个示例字符串:

{three / fifteen / one hundred} this is the first random number, and this is the second, {two / four}
从括号中,我需要返回一个随机值,例如:
One hundred is the first random number, and this is the second, two
我的代码:
function RandElement($str) {
preg_match_all('/{([^}]+)}/', $str, $matches);
return print_r($matches[0]);
}
$str = "{three/fifteen/one hundred} this is the first random number, and this is the second, {two/four}";
RandElement($str);
结果:
(
[0] => {three/fifteen/one hundred}
[1] => {two/four}
)
而且我不太明白接下来要做什么。从数组中取出第一个字符串并通过正则表达式将其传回?

最佳答案

您可以使用 preg_replace_callback :

$str = "{three/fifteen/one hundred} this is the first random number, and this is the second, {two/four}";
echo preg_replace_callback('~\{([^{}]*)}~', function ($x) {
return array_rand(array_flip(explode('/', $x[1])));
}, $str);
PHP demo
请注意,第 1 组使用 ([^{}]*) 捕获模式(并通过 $x[1] 访问)使用 explode('/', $x[1]) 用斜杠分割然后使用 array_rand 选取一个随机值.直接返回值,数组为 array_flip 佩德。

关于php - 用表达式中的一项替换花括号表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64433662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com