【问题标题】:Replace curly braced expression with one item from the expression用表达式中的一项替换花括号表达式
【发布时间】:2021-02-02 14:28:04
【问题描述】:

这是一个示例字符串:

{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}
)

而且我不太明白下一步该做什么。从数组中取出第一个字符串并通过正则表达式将其传回?

【问题讨论】:

标签: php regex random preg-replace-callback


【解决方案1】:

你可以使用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_flipped。

【讨论】:

    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多