如何解决用表达式中的一项替换大括号表达式
这是一个示例字符串:
{three / fifteen / one hundred} this is the first random number,and this is the second,{two / four}
One hundred is the first random number,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,{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
请注意,以([^{}]*)
模式捕获(并通过$x[1]
访问的第1组)使用explode('/',$x[1])
进行斜线分割,然后使用{{3}拾取随机值。 }。要直接返回值,请对该数组进行array_rand
填充。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。