且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式像gmail搜索运算符 - PHP preg_match

更新时间:2022-10-14 19:33:04

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

相关阅读

技术问答最新文章