phpregexrandompreg-replace-callback

Replace curly braced expression with one item from the expression


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?


Solution

  • 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.