Php 如何检测电报命令并获取单独的参数?

Php 如何检测电报命令并获取单独的参数?,php,regex,Php,Regex,如何从该字符串中获取每个参数 Array ( [0] => /register hello world 2021 [1] => register [2] => [3] => hello world 2021 ) 它不会在结果中产生完全匹配,但您知道有通过if子句的匹配 请注意,在您尝试的模式中,@在caputure组之外,是可选的,但是\S本身也可以匹配@ Array ( [0] => /register

如何从该字符串中获取每个参数

Array
(
    [0] => /register hello world 2021
    [1] => register
    [2] => 
    [3] => hello world 2021
)

它不会在结果中产生完全匹配,但您知道有通过if子句的匹配

请注意,在您尝试的模式中,
@
在caputure组之外,是可选的,但是
\S
本身也可以匹配
@

Array
    (
        [0] => /register hello world 2021
        [1] => register
        [2] => hello
        [3] => world
        [4] => 2021
    )
解释

  • (?:
    非捕获组
    • ^/
      匹配字符串开头的
      /
    • |
    • \G(?!^)
      在上一次匹配结束时断言位置
  • 关闭该组
  • [\h@]?\K
    匹配可选空格或@,然后忘记匹配的内容,直到目前为止
  • [^\s@]+
    将任何字符的1+倍匹配,空白字符或空白字符除外@

输出

$message = "/register hello@there world 2021";
if (preg_match_all('~(?:^/|\G(?!^))[\h@]?\K[^\s@]+~', $message, $matches)) {
    print_r($matches[0]);
}

您可以删除
/
并在一个空格上拆分。如果最多有X个可选参数,请添加X个可选组,如in或like
(?:^\/\G(?!^))[\h@?\K[^\s@]+
(?:^/|\G(?!^))[\h@]?\K[^\s@]+
$message = "/register hello@there world 2021";
if (preg_match_all('~(?:^/|\G(?!^))[\h@]?\K[^\s@]+~', $message, $matches)) {
    print_r($matches[0]);
}
Array
(
    [0] => register
    [1] => hello
    [2] => there
    [3] => world
    [4] => 2021
)