1

How can I get values from string and put it into an associative array, where the key must be given wildcard string.

Given template is:

param1/prefix-{wildcard1}/{wildcard2}/param2

Given string is:

param1/prefix-name/lastname/param2

The result must be

array('wildcard1' => 'name', 'wildcard2' => 'lastname');

UPD

I want to implement some route script, and wildcards must be variable names that will be injected to script and they will be loaded dynamically from other classes.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • sounds like you're just trying to do some basic string splitting and parsing. Look here for a starting point http://php.net/manual/en/function.explode.php – Ananth Rao Feb 25 '17 at 12:29
  • no. templates must be added dynamically, and I have no opportunity to know the wildcards names. Only thing is that they must be included in {} delimiters. I want to implement some route script, and wildcards must be variable names that will be injected to script – Mamikon Arakelyan Feb 25 '17 at 12:42

1 Answers1

0

I'd first transform template into regex with named capture group, then do the preg_match.

$template = 'param1/prefix-{wildcard1}/{wildcard2}/param2';
// escape special characters
$template = preg_quote($template, '/');

// first, change all {wildcardN} into (?<wildcardN.*?)
$regex = preg_replace('/\\\{([^}]+)\\\}/', "(?<$1>.*?)", $template);

$string = 'param1/prefix-name/lastname/param2';
// do the preg_match using the regex
preg_match("/$regex/", $string, $match);

print_r($match);

Output:

Array
(
    [0] => param1/prefix-name/lastname/param2
    [wildcard1] => name
    [1] => name
    [wildcard2] => lastname
    [2] => lastname
)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Toto
  • 89,455
  • 62
  • 89
  • 125