如何在 php 中重写字符串并按模式获取参数

How to rewrite a string and get params by pattern in php

$string = '/start info@example.com';
$pattern = '/{command} {name}@{domain}';

获取php中的数组参数,如下例:

['command' => 'start', 'name' => 'info', 'domain' => 'example.com'] 

$string = '/start info@example.com';
$pattern = '/{command} {email}'; 
['command' => 'start', 'email' => 'info@example.com']

$string = '/start info@example.com';
$pattern = '{command} {email}';
['command' => '/start', 'email' => 'info@example.com']

如果它是单行字符串,您可以使用 preg_match 和正则表达式,例如

  preg_match('/^\/(?P<command>\w+)\s(?P<name>[^@]+)\@(?P<domain>.+?)$/', '/start info@example.com', $match );

但根据数据的变化,您可能需要稍微调整 regx。这输出

  • 命令 [1-6] start
  • 名字[7-11]info
  • 域 [12-23] example.com

但它也会在数组中有数字索引。

https://regex101.com/r/jN8gP7/1

只是用英语稍微分解一下。

前导 ^ 是行首,然后命名为 capture ( \w (any a-z A-Z 0-9 _ ) ) 然后是 space \s 然后命名捕获(除 @t 符号 [^@] 之外的任何内容),然后是 @t 符号 @,然后捕获名称(任何 .+? 到结尾 $

这将捕获此格式的任何内容,

(abc123_ ) space (除了@)@(任何)