2011-02-04 59 views
1

我想實現一個類似於gmail搜索運算符的系統,使用PHP中的函數preg_match來分割輸入字符串。 實施例:像gmail搜索運算符的正則表達式 - PHP preg_match

輸入字符串 =>命令1:WORD1 WORD2命令2:WORD3命令3:word4 wordN
輸出數組 =>(
命令1:WORD1 word2和
命令2:WORD3,
指令代碼3: word4 wordN

以下文章解釋如何做到這一點:Implementing Google search operators

我已經使用preg_match測試了它,但不匹配。我認爲正則表達式可能會在系統之間發生一些變化。
任何猜測PHP中的正則表達式如何匹配這個問題?

preg_match('/\s+(?=\w+:)/i','command1:word1 word2 command2:word3 command3:word4 wordN',$test); 

感謝,

+0

pre_split而不是preg_match會做正確 – cmancre 2011-02-04 11:00:19

+0

實際上(至少今天是2016-07-27)當條件中有特殊字符時,gmail會添加括號:`to:([email protected])subject:(testing other字)from:test` – 2016-07-27 13:26:37

回答

2

您可以使用這樣的事情:

<?php 
$input = 'command1:word1 word2 command2:word3 command3:word4 wordN command1:word3'; 
preg_match_all('/ 
    (?: 
    ([^: ]+) # command 
    : # trailing ":" 
) 
    (
    [^: ]+ # 1st word 
    (?:\s+[^: ]+\b(?!:))* # possible other words, starts with spaces, does not end with ":" 
) 
    /x', $input, $matches, PREG_SET_ORDER); 

$result = array(); 
foreach ($matches as $match) { 
    $result[$match[1]] = $result[$match[1]] ? $result[$match[1]] . ' ' . $match[2] : $match[2]; 
} 

var_dump($result); 

它將應付,即使在不同的位置相同的命令(例如,「命令1:」在開始和結束都)。