我想替换方括号中的所有字符串([]
)以及从名为该字符串的数组中随机选择的项目。
它非常类似于这个问题,但有一点不同,因为我想用名为该数组的字符串替换不同括号的内容。
一个例子应该会让这一点更清楚一些。
所以说我已经拿到了字符串
"This is a very [adjective] [noun], and this is a [adjective] [noun]."
和变量:
$adjective = array("big","small","good","bad");
$noun = array("house","dog","car");
我们希望它回归"This is a very big house, and this is a good dog."
或者其他什么,通过随机选择。也就是说,我想编写一个 PHP 函数来替换每个[string]
从名为的数组中随机选择一个项目$string
。现在,随机选择是否会导致重复选择并不重要,但它必须为每个选择做出新的选择[]
item.
我希望我已经解释清楚了。如果您得到我想要实现的目标并且能想出更好的方法来实现它,我将非常感激。
算法
- 匹配此正则表达式:
(\[.*?\])
- 对于每个匹配组,从相关数组中选择一个项目。
- 按顺序替换字符串。
执行
$string = "This is a very [adjective] [noun], and this is a [adjective] [noun].";
$adjective = array("big","small","good","bad");
$noun = array("house","dog","car");
// find matches against the regex and replaces them the callback function.
$result = preg_replace_callback(
// Matches parts to be replaced: '[adjective]', '[noun]'
'/(\[.*?\])/',
// Callback function. Use 'use()' or define arrays as 'global'
function($matches) use ($adjective, $noun) {
// Remove square brackets from the match
// then use it as variable name
$array = ${trim($matches[1],"[]")};
// Pick an item from the related array whichever.
return $array[array_rand($array)];
},
// Input string to search in.
$string
);
print $result;
解释
预替换回调函数使用提供的回调函数执行正则表达式搜索和替换。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)