mehdi mehdi - 5 months ago 11
PHP Question

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

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


get array params in php, Like the example below:

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


and

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


and

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

Answer

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 info@example.com', $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] example.com

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

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

Comments