permutation using regular expression in php(在php中使用正则表达式进行排列)
                            本文介绍了在php中使用正则表达式进行排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
有没有办法只使用php中的正则表达式来获得字符串中所有单词的排列。
例如:
输入"如何消除人体膝盖疼痛"
我希望输出为:
"如何"、"如何"、"膝部疼痛"、"移除膝部"、"膝部疼痛"、"正在移除"、"人体膝部疼痛"等
推荐答案
使用正则表达式只会减慢进程。
我已经根据Yada@https://stackoverflow.com/a/27968556/2943403发布的powerSet()函数编写了一个函数
编码:(Demo)
function permStacker($array){
    $stack=[[]];  // declare intitial empty element
    foreach($array as $element){
        foreach($stack as $combination){
            foreach(array_diff($array,$combination) as $left){
                $merge=array_merge($combination,[$left]);
                $stack[implode(' ',$merge)]=$merge;  // keys hold desired strings, values hold subarray of combinations for iterated referencing
            }
        }
    }
    unset($stack[0]); // remove initial empty element
    return array_keys($stack);  // return array of permutations as space delimited strings
}
$string='How to remove pain in human knee';
$permutations=permStacker(explode(' ',$string));
echo 'Total Permutations: ',sizeof($permutations),"
";
var_export($permutations);
输出:
Total Permutations: 13699
array (
  0 => 'How',
  1 => 'to',
  2 => 'remove',
  3 => 'pain',
  4 => 'in',
  5 => 'human',
  6 => 'knee',
  7 => 'How to',
  8 => 'How remove',
  9 => 'How pain',
  10 => 'How in',
  11 => 'How human',
  12 => 'How knee',
  13 => 'to How',
  14 => 'to remove',
  15 => 'to pain',
  16 => 'to in',
  17 => 'to human',
  18 => 'to knee',
  19 => 'remove How',
  20 => 'remove to',
  21 => 'remove pain',
  22 => 'remove in',
  23 => 'remove human',
  24 => 'remove knee',
  25 => 'pain How',
  26 => 'pain to',
  27 => 'pain remove',
  28 => 'pain in',
  29 => 'pain human',
  30 => 'pain knee',
  31 => 'in How',
  32 => 'in to',
  33 => 'in remove',
  34 => 'in pain',
  35 => 'in human',
  36 => 'in knee',
  37 => 'human How',
  38 => 'human to',
  39 => 'human remove',
  40 => 'human pain',
  41 => 'human in',
  42 => 'human knee',
  43 => 'knee How',
  44 => 'knee to',
  45 => 'knee remove',
  46 => 'knee pain',
  47 => 'knee in',
  48 => 'knee human',
  49 => 'How to remove',
  50 => 'How to pain',
  51 => 'How to in',
这里是bob at math.stackexchange发布的一篇文章,它确认当输入字符串中给出7个单词时,13699是返回数组的预期大小。此外,Bob的崩溃应该作为一个警告,告诉我们排列是如何快速增长的--注意您的大字符串。
这篇关于在php中使用正则表达式进行排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:在php中使用正则表达式进行排列
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 - Web 服务器如何处理请求? 2021-01-01
 - 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - php中的foreach复选框POST 2021-01-01
 - php中的PDF导出 2022-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - Yii2 - 在运行时设置邮件传输参数 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				