Replace curly braced expression with one item from the expression

蹲街弑〆低调 提交于 2021-02-16 20:30:17

问题


Here is a sample string:

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

From the brackets, I need to return a random value for example:

One hundred is the first random number, and this is the second, two

My code:

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);

Result:

(
    [0] => {three/fifteen/one hundred}
    [1] => {two/four}
)

And I don't quite understand what to do next. Take the first string from an array and pass it back through a regex?


回答1:


You can use 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);

See the PHP demo

Note that Group 1 captured with the ([^{}]*) pattern (and accessed via $x[1]) is split with a slash using explode('/', $x[1]) and then a random value is picked up using array_rand. To return the value directly, the array is array_flipped.



来源:https://stackoverflow.com/questions/64433662/replace-curly-braced-expression-with-one-item-from-the-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!