Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP从数组中获取值/随机字生成器/将字符串拆分为数组_Php_Arrays - Fatal编程技术网

PHP从数组中获取值/随机字生成器/将字符串拆分为数组

PHP从数组中获取值/随机字生成器/将字符串拆分为数组,php,arrays,Php,Arrays,我有一个句子需要随机改变花括号中的部分。重要的一点是大括号内的值可以更改(就像您可以在其中放入任何单词一样),因此 当我使用 $parts = explode('{', $x); 它给了我一个如下的数组 数组([0]=>[1]=>{请,|只要|如果可以,}这样做,这个 [2] =>难以置信的|酷|简单|重要|无用|句子 [3] =>快速|正确|即时}每次随机更改) 这不管用 我所做的是: $parts = [ ['Please,','Just','If you can,'],

我有一个句子需要随机改变花括号中的部分。重要的一点是大括号内的值可以更改(就像您可以在其中放入任何单词一样),因此

当我使用

$parts = explode('{', $x); 
它给了我一个如下的数组

数组([0]=>[1]=>{请,|只要|如果可以,}这样做,这个 [2] =>难以置信的|酷|简单|重要|无用|句子 [3] =>快速|正确|即时}每次随机更改)

这不管用

我所做的是:

 $parts = [

  ['Please,','Just','If you can,'], 

  ['incredible', 'cool','simple','important','useless'],

  ['fast','correctly','instantly'],

];

$p = [];

foreach ($parts as $key => $values) {

  $index = array_rand($values, 1);

  $p[$key] = $values[$index];
}


  $x_one = $p[0] . ' make it so that ' .  $p[1] . ' this sentence

changed ' . $p[2] . ' randomly every time.';

echo $x_one;  
我必须从
$x
获取
$parts
,因为字符串
$x
中的单词可以更改。不知道从这里走到哪里。

您可以使用捕获序列,使用
|
拆分并返回一个随机值:

$x = '{Please,|Just|If you can,} make so, that this

{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly}

changed randomly every time';

// catch all strings that match with {...}
$str = preg_replace_callback('~\{([^}]+)\}~', function($matches){
    // split using |
    $pos = explode('|', $matches[1]);
    // return random element
    return $pos[array_rand($pos)];
}, $x);

echo $str;
可能的产出:

  • 如果可以的话,让这个很酷的句子每次都能正确地随机改变
  • 请,让这个酷句子每次都随机快速变化
  • 如果可以的话,让这个不可思议的句子每次都随机快速地改变
正则表达式:

\{       # { character
 (       # capture group
 [^}]+   # all character until }
 )       # end capture group
\}       # } character

另一种方法可以如下所示:

    $output = $input = '{Please,|Just|If you can,} make so, that this 

{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly} 

changed randomly every time';


/**
 * Will output
 *  0 => string '{Please,|Just|If you can,}' (length=26)
 * 1 => string '{incredible|cool|simple|important|useless}' (length=42)
 * 2 => string '{fast|correctly|instantly}' (length=26)
 */
preg_match_all('/\{([^}]+)\}/',$input,$m);
foreach ($m[1] as $index => $rotateWord) {
    $words = explode('|',$rotateWord); //Split by pipe each words founds
    $randomWord = $words[rand(0, count($words) - 1)]; // Select random word.
    $output = str_replace($m[0][$index], $randomWord, $output);
}

var_dump($output);

正则表达式在这些情况下非常有用。例如,它在解析器中用于查找标记

在本例中,您希望获得大括号之间的所有子字符串。 这就是诀窍:

$matches = array();
preg_match_all('/\{([^}]*)\}/', $x, $matches);
print_r($matches);
输出:

Array
(
    [0] => Array
        (
            [0] => {Please,|Just|If you can,}
            [1] => {incredible|cool|simple|important|useless}
            [2] => {fast|correctly|instantly}
        )

    [1] => Array
        (
            [0] => Please,|Just|If you can,
            [1] => incredible|cool|simple|important|useless
            [2] => fast|correctly|instantly
        )
)
表达式
'/\{([^}]*)\}/
表示:

  • /
    :这可以是任何字符
  • \{
    :从开始大括号开始
  • ([^}]+)
    :不是结束大括号的所有内容(括号用于分隔匹配的表达式,这就是结果位于数组的索引号1中的原因)
  • \}
    :用一个末端卷曲的大括号结束
  • /
    :它必须与第一个字符相同
换句话说:在花括号之间的任何东西

您可以在或处测试正则表达式

但这还不够:你想替换那些匹配项
preg_replace
可以做到这一点,但这还不够,因为还需要调用一些函数来选择随机子字符串
preg\u replace\u callback
可以做到这一点

<?php

$x = '{Please,|Just|If you can,} make so, that this 

{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly} 

changed randomly every time';

echo preg_replace_callback(
    '/\{([^\}]+)\}/',
    function ($matches) {
        $options = explode('|', $matches[1]);
        return $options[array_rand($options)];
    },
    $x
);

如果大括号内的值可以更改,实际上,最好将它们从模板提取到数组中,就像您在问题中所做的那样。有了零件数组和模板字符串,您就可以与以下内容一起使用:


这是。

谢谢!我以前从未使用过preg\u replace\u callback()。谢谢你的解释。我需要它谢谢你提供的所有有用的信息,我真的很感激。
<?php

$x = '{Please,|Just|If you can,} make so, that this 

{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly} 

changed randomly every time';

echo preg_replace_callback(
    '/\{([^\}]+)\}/',
    function ($matches) {
        $options = explode('|', $matches[1]);
        return $options[array_rand($options)];
    },
    $x
);
$parts = [
  '%part1%' => ['Please,','Just','If you can,'], 

  '%part2%' => ['incredible', 'cool','simple','important','useless'],

  '%part3%' => ['fast','correctly','instantly'],
];

$template = '%part1% make so, that this %part2% sentence %part3% changed randomly every time';

$result = strtr($template, array_map(function ($values) {
    return $values[array_rand($values, 1)];
}, $parts));