在 PHP 中用如此命名的变量替换括号内的文本 [英] Replace text within brackets with thus-named variable in PHP

查看:47
本文介绍了在 PHP 中用如此命名的变量替换括号内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这个问题非常相似,但有一点需要注意的是,我想用名为 that 的数组中的字符串替换不同括号的内容.

举个例子应该会更清楚一点.

所以说我得到了字符串

这是一个非常[形容词] [名词],这是一个[形容词] [名词]."

和变量:

$adjective = array("big","small","good","bad");$noun = array("house","dog","car");

我们希望它通过随机选择返回这是一所很大的房子,这是一只好狗." 或其他任何东西.也就是说,我想编写一个 PHP 函数,它将用从名为 $string 的数组中随机选择的项目替换每个 [string].目前,随机选择是否会导致重复选择并不重要,但它必须为每个 [] 项目做出新的选择.

我希望我已经解释清楚了.如果您明白我想要达到的目标并且能想到更好的方法,我将不胜感激.

解决方案

算法

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

实施

$string = "这是一个非常[形容词] [名词],这是一个[形容词] [名词].";$adjective = array("big","small","good","bad");$noun = array("house","dog","car");//查找正则表达式的匹配项并将它们替换为回调函数.$result = preg_replace_callback(//匹配要替换的部分:'[adjective]', '[noun]''/(\[.*?\])/',//回调函数.使用 'use()' 或将数组定义为 'global'函数($matches)使用($形容词,$名词){//从匹配中删除方括号//然后将其用作变量名$array = ${trim($matches[1],"[]")};//从相关数组中选择一个项目.返回 $array[array_rand($array)];},//输入要搜索的字符串.$字符串);打印 $result;

说明

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

  • 第一个参数是要匹配的正则表达式(斜线括起来):/(\[.*?\])/

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

    • 我们必须在这里使用 use() 从函数内部访问数组,或者将数组定义为全局:global $adjective = ....即,我们必须执行以下操作之一:

      a) 将数组定义为 global:

      <前>...global $adjective = array("big","small","good","bad");global $noun = array("house","dog","car");...功能($匹配){...

      b) 使用use:

      <前>...$adjective = array("big","small","good","bad");$noun = array("house","dog","car");...函数($matches)使用($形容词,$名词){...

    • 回调函数的第一行:

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

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

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

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

I want to replace all strings in square brackets ([]) with a randomly chosen item from an array that's named that string.

It's very similar to this issue, but with a twist, in that I want to replace different brackets' contents with strings from arrays named that.

An example should make this a bit clearer.

So say I've got the string

"This is a very [adjective] [noun], and this is a [adjective] [noun]."

And the variables:

$adjective = array("big","small","good","bad");
$noun      = array("house","dog","car");

And we want it to return "This is a very big house, and this is a good dog." or whatever, by choosing randomly. That is, I want to write a PHP function that will replace each [string] with a randomly chosen item from the array named $string. For now it doesn't matter if by randomly choosing it ends up repeating choices, but it must make a fresh choice for each [] item.

I hope I've explained this clearly. If you get what I'm trying to achieve and can think of a better way to do it I'd be very grateful.

解决方案

Algorithm

  1. Match for this regex: (\[.*?\])
  2. For each match group pick an item from the related array.
  3. Replace in string by order.

Implementation

$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;

Explanation

preg_replace_callback function performs a regular expression search and replace using provided callback function.

  • First parameter is regular expression to match (enclosed between slashes): /(\[.*?\])/

  • Second parameter is callback function to call for each match. Takes the current match as parameter.

    • We have to use use() here to access the arrays from inside the function, or define the arrays as global: global $adjective = .... Namely, we have to do one of the followings:

      a) Define arrays as global:

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

      b) Use use:

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

    • First line of the callback function:

      • trim: Removes square brackets ([]) from the match using trim function.

      • ${}: Creates a variable to use as array name with the match name. For example, if the $match is [noun] then trim($matches[1],"[]") returns noun (without brackets) and ${noun} becomes the array name: $noun. For more information on the topic, see variable variables.

    • Second line randomly picks an index number available for the $array and then returns the element at this position.

  • Third parameter is the input string.

这篇关于在 PHP 中用如此命名的变量替换括号内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆