PHP:按文本中的值出现排序数组?

时间:2015-11-18 15:06:43

标签: php arrays regex sorting

我需要按照文本字符串中出现的顺序来排序未知的关键字数组。

// 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 );

解决方案可能包括'preg_match`,但我不知道从哪里开始。

3 个答案:

答案 0 :(得分:2)

  1. 首先从字符串中提取单词(我假设每个关键字都出现在文本中的单独行中)

    preg_match_all('/[ \t]*\(\((.*)\)\)[ \t]*/', $text, $matches);`
    
  2. 然后您获取生成的数组并与关键字

    相交
    if (isset($matches[1])) {
      $results = array_intersect($matches[1], $keywords);
    }
    
  3. 以下是完整代码段(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);
    

答案 1 :(得分:0)

尝试类似:

$keywordsPos = array();
//find the pos of the first occurrence of each word 
foreach ($keywords as $keyword) {
  $keywordsPos[$keyword] = strpos($text, $keyword);
}
//sort the keywords by their pos
asort($keywordsPos);
//drop the pos but keep the keywords in order. 
$result = array_values(array_flip($keywordsPos));

答案 2 :(得分:-1)

您可以使用' usort'功能:

$keywords = array( "orange", "apple", "banana" );

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

((foo))
((banana))
((orange))
((baz))
((apple))
((baz))
";

usort($keywords, function ($a, $b) use($text) {
    $countA = substr_count($text, $a);
    $countB = substr_count($text, $b);
    if($countA == $countB)
        return 0;
    return $countA > $countB ? 1 : -1;
});

var_dump($keywords);

输出:

array(3) {
  [0]=>
  string(6) "orange"
  [1]=>
  string(6) "banana"
  [2]=>
  string(5) "apple"
}