doukang7501 2015-11-18 15:06
浏览 13
已采纳

PHP:按文本中的值出现排序数组? [关闭]

I need to order an unknown array of keywords by the order they occur in a text string.

// random order of unknown values
$keywords = array( "orange", "green apple", "banana" );

// ordered occurrences
$text = "This is text where the keywords can appear as well like green apple trees.
Then follows text where the keywords are in order and surrounded by unique syntax.

((randomly ordered keywords))
((foo))
((banana))
((orange))
((baz))
((green apple))
((baz))
";

// reorder keywords
// maybe preg_match( "/.+\({2}(".$keywordItem.")\).*/", $text, $matches )
// ...


// Order should be banana, orange, green apple
print_r( $keywords );

The solution may include ´preg_match`, but I don't know where to start.

  • 写回答

3条回答 默认 最新

  • doupai1876 2015-11-18 15:26
    关注
    1. First extract the words from the string (I'm assuming each keyword appears in the text in it's own separate line)

      preg_match_all('/[ \t]*\(\((.*)\)\)[ \t]*/', $text, $matches);`
      
    2. Then you take the produced array and intersect with the keywords

      if (isset($matches[1])) {
        $results = array_intersect($matches[1], $keywords);
      }
      

    Here's the complete snippet (php pad):

    $keywords = array( "orange", "green apple", "banana" );
    
    $text = "This is text where the keywords can appear as well like green apple trees.
    The follows text where the keywords are in order and surrounded by unique syntax.
    
    ((randomly ordered keywords))
    ((foo))
    ((banana))
    ((orange))
    ((baz))
    ((green apple))
    ((baz))
    ";
    
    // extract keywords
    $matches = array();
    $results = array();
    preg_match_all('/[ \t]*\(\((.*)\)\)[ \t]*/', $text, $matches);
    
    // Sort keywords
    if (isset($matches[1])) {
      $results = array_intersect($matches[1], $keywords);
    }
    
    var_dump($results);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?