正则表达式像gmail搜索运算符 - PHP preg_match [英] regex like gmail search operators - PHP preg_match
问题描述
我试图使用PHP中的函数preg_match来实现一个类似于gmail搜索操作符的系统来分割输入字符串。
示例:
输入字符串 => command1:word1 word2 command2:word3 command3:word4 wordN
输出数组 =>(
command1:word1 word2,
command2:word3,
command3:word4 wordN
)
以下文章解释了如何执行此操作:实现Google搜索运算符
我已经使用preg_match对其进行了测试,但不匹配。我认为正则表达式可能会有所不同,从系统到系统。
任何猜测PHP中的正则表达式如何匹配这个问题?
preg_match('/ \ s +(?= \w +:)/ i','command1:word1 word2 command2: word3 command3:word4 wordN',$ test);
谢谢,
<?php
$ input ='command1 :word1 word2 command2:word3 command3:word4 wordN command1:word3';
preg_match_all('/
(?:
([^:] +)#command
:#trailing:
)
(
[^:] +#第一个单词
(?:\s + [^:] + \b(?!:))*#可能的其他单词,以空格开头,不以:
)
/ x',$ input,$ matches,PREG_SET_ORDER);
$ result = array();
foreach($ match为$ match){
$ result [$ match [1]] = $ result [$ match [1]]? $ result [$ match [1]]。 ''。 $ match [2]:$ match [2];
}
var_dump($ result);
即使在不同位置使用相同命令(例如,command1:并结束)。
I'm trying to implement a system similar to gmail search operators using function preg_match from PHP to split the input string . Example:
input string => command1:word1 word2 command2:word3 command3:word4 wordN
output array => (
command1:word1 word2,
command2:word3,
command3:word4 wordN
)
The following post explains how to do it: Implementing Google search operators
I already test it using preg_match but doesn't match. I think regular expressions may change a bit from system to system.
Any guess how regex in PHP would match this problem?
preg_match('/\s+(?=\w+:)/i','command1:word1 word2 command2:word3 command3:word4 wordN',$test);
Thanks,
You can use something like this:
<?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);
It will cope even with same commands at different locations (eg. "command1:" at both the start and end).
这篇关于正则表达式像gmail搜索运算符 - PHP preg_match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!