mehdi mehdi - 3 months ago 5x
PHP Question

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

$string = '/start';
$pattern = '/{command} {name}@{domain}';

get array params in php, Like the example below:

['command' => 'start', 'name' => 'info', 'domain' => '']


$string = '/start';
$pattern = '/{command} {email}';
['command' => 'start', 'email' => '']


$string = '/start';
$pattern = '{command} {email}';
['command' => '/start', 'email' => '']


If its a single line string you can use preg_match and a regular expression such as this

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

But dependaing on variation in the data you may have to adjust the regx a bit. This outputs

  • command [1-6] start
  • name [7-11] info
  • domain [12-23]

but it will also have the numeric index in the array.