繁体   English   中英

如何在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 (任何az AZ 0-9 _)),然后是一个空格\\s然后命名为capture of(除@t符号[^@] ),然后是@t在@签名,然后捕获的名称(任何.+?$结尾)

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

(abc123_)空间(@除外)@(任何东西)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM