【问题标题】:need to create an random sentence from a given sentence需要从给定句子中创建一个随机句子
【发布时间】:2014-01-16 07:08:35
【问题描述】:

下面的句子,

{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}

我需要创建一个 random() 函数,它将给出以下输出:-

Please make this cool test sentence rotate fast and random.
OR
Just make this random test sentence spin and be random.

我不知道该怎么做。

我在下面尝试过,但没有得到结果。

echo spinningFunction($str);

function spinningFunction($str)
{
    $output = "";
    $pattern = "/\[.*?\]|\{.*?\}/";
    preg_match_all($pattern, $str, $match);

    $arr = array_map(function($value){
        return explode("|", $value);
    }, $match[1]);


    foreach($arr[0] as $adj)
        foreach($arr[1] as $name)
            $output.= "{$adj} make this {$name} test sentence<br />";
    return $output;
}

有什么帮助吗?

编辑:-

function spinningFunction($str)
{
    $str = preg_replace_callback('/(\{[^}]*)([^{]*\})/im', "spinningFunction", $str);
    return $str;
}

有人能帮我从上面的句子中实现如下所示的数组吗:-

Array
(
    [0] => Array
        (
            [0] => {Please|Just}
            [1] => {cool|awesome|random}
            [2] => {rotate {quickly|fast} and random|spin and be random}
        )
)

【问题讨论】:

  • 您的正则表达式中没有任何捕获组,因此$match[1] 不包含任何内容。你想要$match[0]
  • 你的随机码在哪里?你只是输出每个组合。请参阅 stackoverflow.com/questions/4233407/get-random-item-from-array 了解如何选择数组的随机元素。
  • 是的。但 $match[0] 也没有给我数组中的确切 3 元素:(
  • @Barmar 尚未应用。实际上,到目前为止,我还无法迈出第一步。 :(
  • @Barmar 请查看我编辑的代码。我试图使用类似的代码

标签: php regex function random-sample


【解决方案1】:

这是一个解决方案,需要对嵌套集使用语法 {a|[b|c]}。它也只能手动深入一层,因此没有干净/简单的递归。不过,根据您的用例,这可能没问题。

function randomizeString($string)
{
    if(preg_match_all('/(?<={)[^}]*(?=})/', $string, $matches)) {
        $matches = reset($matches);
        foreach($matches as $i => $match) {
            if(preg_match_all('/(?<=\[)[^\]]*(?=\])/', $match, $sub_matches)) {
                $sub_matches = reset($sub_matches);
                foreach($sub_matches as $sub_match) {
                    $pieces = explode('|', $sub_match);
                    $count = count($pieces);

                    $random_word = $pieces[rand(0, ($count - 1))];
                    $matches[$i] = str_replace('[' . $sub_match . ']',     $random_word, $matches[$i]);
                }
            }

            $pieces = explode('|', $matches[$i]);
            $count = count($pieces);

            $random_word = $pieces[rand(0, ($count - 1))];
            $string = str_replace('{' . $match . '}', $random_word, $string);
        }
    }

    return $string;
}

var_dump(randomizeString('{Please|Just} make this {cool|awesome|random} test sentence {rotate [quickly|fast] and random|spin and be random}.'));
// string(53) "Just make this cool test sentence spin and be random."

var_dump(randomizeString('You can only go two deep. {foo [bar|foo]|abc 123}'));
// string(33) "You can only go two deep. foo foo"

【讨论】:

  • 非常感谢。它运行良好。这个逻辑太棒了。
  • 1 个问题。如何从输出字符串中消除“string(53)”?
【解决方案2】:

您必须注意嵌套匹配(请参阅http://php.net/manual/en/regexp.reference.recursive.php 中的递归模式)。试试这个

function spinningFunction($str)
{

    $output = "";
    $pattern = "/{(?:[^{}]+|(?R))*}/";
    preg_match_all($pattern, $str, $match);
    print_r($match[0]);

}

$s = "{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}";

spinningFunction($s);

模式解释{(?:[^{}]+|(?R))*}

{ matches the character { literally

(?:[^{}]+|(?R))* Non-capturing group
 Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

    1st Alternative: [^{}]+
     [^{}]+ match a single character not present in the list below
     Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
     {} a single character in the list {} literally

    2nd Alternative: (?R)
     (?R) recurses the entire pattern

} matches the character } literally

【讨论】:

    【解决方案3】:

    这是您要查找的内容:

    类似这样的:

    $text = '{Please|Just} make this {cool|awesome|random} test sentence {rotate|spin) {quickly|fast} and {randomize|spin} the text';
    
    echo 'input-text:<br />'.$text.'<br />';  //echo original string for text output purposes.
    
    $openingConstruct = '{';
    $closingConstruct = '}';
    $separator = '|';
    
    if(preg_match_all('!'.$openingConstruct.'(.*?)'.$closingConstruct.'!s', $text, $matches)){
      $find = array();
      $replace = array();
    
      foreach($matches[0] as $key => $match){
        $choices = explode($separator, $matches[1][$key]);
        $find[] = $match;
        $replace[]  = $choices[mt_rand(0, count($choices) - 1)]; 
    
        foreach($find as $key => $value){
           if(($pos = mb_strpos($text, $value)) !== false) {
    
           if(!isset($replace[$key])){
              $replace[$key] = '';
           }
    
           $text = mb_substr($text, 0, $pos).$replace[$key].mb_substr($text, $pos + mb_strlen($value));
        }
        }
    }
    
      echo 'output-text:<br />'.$text;
    }
    

    输出:

    input-text:
    {Please|Just} make this {cool|awesome|random} test sentence {rotate|spin) {quickly|fast} and {randomize|spin} the text
    
    output-text:
    Just make this random test sentence rotate and randomize the text
    

    【讨论】:

      【解决方案4】:

      以下是您可以使用任意多级嵌套的方法:

      function rand_replace($str)
      {
          $pattern = "/{([^{}]*)}/";
          while (preg_match_all($pattern, $str, $matches) > 0) {
              for ($i = 0; $i < count($matches[1]); $i++) 
              {
                  $options = explode('|', $matches[1][$i]);
                  $rand_option = $options[rand(0, count($options)-1)];
                  $str = str_replace($matches[0][$i], $rand_option, $str);
              }
          }
          return $str;
      }
      

      它首先匹配最深的嵌套交替,用其中一个选项随机替换它,然后逐步退出,直到整个字符串被随机化。

      使用您的示例输入的几次运行的输出:

      Just make this random test sentence rotate fast and random
      Please make this random test sentence spin and be random
      Please make this cool test sentence rotate fast and random
      Just make this random test sentence spin and be random
      Please make this awesome test sentence spin and be random
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-09
        • 2021-12-10
        • 2022-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多