2011-02-04 58 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:”在开始和结束都)。