regex like gmail search operators - PHP preg_match

北战南征 提交于 2019-12-06 12:28:49

问题


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,


回答1:


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).



来源:https://stackoverflow.com/questions/4897060/regex-like-gmail-search-operators-php-preg-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!