【问题标题】:PHP regex generatorPHP 正则表达式生成器
【发布时间】:2011-08-17 09:59:33
【问题描述】:

我现在有一个符合以下所需条件的正则表达式字符串:

一个单行 php-ready 正则表达式,包含许多关键字和关键字,并且将匹配其中至少一个。

例如:

关键词:

  • apple
  • banana
  • strawberry
  • pear cake

现在,如果找到这些关键术语中的任何一个,则返回 true。但是,为了增加一点难度,pear cake 术语应拆分为两个关键字,它们必须都在字符串中,但不必在一起。

应该返回 true 的示例字符串:

  • A great cake is made from pear
  • i like apples
  • i like apples and bananas
  • i like cakes made from pear and apples
  • I like cakes made from pears

有效的正则表达式是:

/\bapple|\bbanana|\bstrawberry|\bpear.*?\bcake|\bcake.*?\bpear/

现在我需要一个 php 函数,它可以从一组关键术语中即时创建这个正则表达式。坚持者是关键字可以在该关键字中包含任意数量的关键字。只需要找到一个关键字,但可以存在多个。如上所述,关键字中的所有单词必须以任意顺序出现在字符串中。

【问题讨论】:

    标签: php regex generator


    【解决方案1】:

    我在这里为你写了一个函数:

    <?php
    
    function permutations($array)
    {
     $list = array();
     for ($i=0; $i<=10000; $i++) {
      shuffle($array);
      $tmp = implode(',',$array);
      if (isset($list[$tmp])) {
       $list[$tmp]++;
      } else {
       $list[$tmp] = 1;
      }
     }
     ksort($list);
     $list = array_keys($list);
     return $list;
    }
    
    
    
    function CreateRegex($array)
    {
        $toReturn = '/';
        foreach($array AS $value)
        {
            //Contains spaces
            if(strpos($value, " ") != false)
            {
                $pieces = explode(" ", $value);
                $combos = permutations($pieces);
                foreach($combos AS $currentCombo)
                {
                    $currentPieces = explode(',', $currentCombo);
                    foreach($currentPieces AS $finallyGotIt)
                    {
                        $toReturn .= '\b' . $finallyGotIt . '.*?';
                    }
                    $toReturn = substr($toReturn, 0, -3) . '|';
                }
            }
            else
            {
                $toReturn .= '\b' . $value . '|';
            }
        }
    
        $toReturn = substr($toReturn, 0, -1) . '/';
        return $toReturn;
    }
    
    
    
    
    var_dump(CreateRegex(array('apple', 'banana', 'strawberry', 'pear cake')));
    
    ?>
    

    我的排列函数来自:

    http://www.hashbangcode.com/blog/getting-all-permutations-array-php-74.html

    但我建议找一个更好的函数并使用另一个函数,因为乍一看这个函数非常难看,因为无论如何它都会将 $i 增加到 10,000。

    另外,这里是代码的键盘:

    http://codepad.org/nUhFwKz1

    如果有问题请告诉我!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2016-08-19
      • 2017-09-23
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多