用PHP中这样命名的变量替换括号内的文本

1 php regex string replace

我想[]用一个名为该字符串的数组中随机选择的项替换方括号()中的所有字符串.

它与这个问题非常相似,但有一个转折,因为我想用名为的数组中的字符串替换不同的括号内容.

一个例子应该让这一点更清晰.

所以说我有字符串

"This is a very [adjective] [noun], and this is a [adjective] [noun]."
Run Code Online (Sandbox Code Playgroud)

变量:

$adjective = array("big","small","good","bad");
$noun      = array("house","dog","car");
Run Code Online (Sandbox Code Playgroud)

我们希望"This is a very big house, and this is a good dog."通过随机选择返回或其他任何东西.也就是说,我想编写一个PHP函数,它将[string]使用名为的数组中随机选择的项替换每个函数$string.现在,如果通过随机选择它最终重复选择并不重要,但它必须为每个[]项目做出新的选择.

我希望我已经清楚地解释了这一点.如果你得到了我想要达到的目标,并且可以想到一个更好的方法来做到这一点,我将非常感激.

mmd*_*bas 8

算法

  1. 匹配此正则表达式: (\[.*?\])
  2. 对于每个匹配组,从相关数组中选择一个项目.
  3. 按顺序替换字符串.

履行

$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;
Run Code Online (Sandbox Code Playgroud)

说明

preg_replace_callback函数使用提供的回调函数执行正则表达式搜索和替换.

  • 第一个参数是匹配的正则表达式(包含在斜杠之间):/(\[.*?\])/

  • 第二个参数是为每个匹配调用的回调函数.将当前匹配作为参数.

    • 我们必须在use()这里使用从函数内部访问数组,或者将数组定义为global : global $adjective = .... 也就是说,我们必须做以下其中一项:

      a)将数组定义为global:

        ...
        global $adjective = array("big","small","good","bad");
        global $noun      = array("house","dog","car");
        ...
        function($matches) {
        ...
      

      b)使用use:

        ...
        $adjective = array("big","small","good","bad");
        $noun      = array("house","dog","car");
        ...
        function($matches) use ($adjective, $noun) {
        ...
      
    • 回调函数的第一行:

      • trim:[]使用trim函数从匹配中删除方括号().

      • $ {}:创建一个变量以用作具有匹配名称的数组名称.例如,如果$match[noun]trim($matches[1],"[]")返回noun(不带括号)和${noun}成为阵列名称:$noun.有关该主题的更多信息,请参阅变量变量.

    • 第二行随机选择一个可用的索引号$array,然后返回该位置的元素.

  • 第三个参数是输入字符串.