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

Replace curly braced expression with one item from the expression

这是一个示例字符串:

{three / fifteen / one hundred} this is the first random number, and this is the second, {two / four}

从括号中,我需要return一个随机值,例如:

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]) 用斜线分割,然后使用 [= 选取一个随机值19=]佩德。