简体   繁体   中英

How could I replace a substring with a variable?

I have a string in the following format:

$string = 'I am {{[1,100]}}'

How could I add to this and replace instances of {{[x,y]}} with a random integer between those values?

In the example provided, the string would become:

$string = 'I am 47'

Use preg_replace_callback() . This uses a function to compute the replacement from the matched part of the input. The function can use rand() to return a random number in the given range, which come from the capture groups in the regexp.

$string = preg_replace_callback('/\{\{\[(\d+),(\d+)\]\}\}/', function($matches) {
    return rand($matches[1], $matches[2]);
}, $string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM