PHP Extract Values From One String Based on a Pattern Defined in Another
I have two strings:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
And I'm trying to get this:
$params = array('param1' => 'is', 'param2' => 'string');
But getting from point a to b is proving more than my tired brain can handle at the moment.
Anything starting with a ':' in the second string defines a variable name/position. There can be any number of variables in $seco开发者_StackOverflow中文版nd which need to be extracted from $first. Segments are separated by a '/'.
For fun I'll throw in a slightly different approach. It takes about half the time as cletus's (whose answer is excellent) because it uses less regex and conditionals:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
$firstParts = explode('/', $first);
$paramKeys = preg_grep('/^:.+/', explode('/', $second));
$params = array();
foreach ($paramKeys as $key => $val) {
$params[substr($val, 1)] = $firstParts[$key];
}
/*
output:
Array
(
[param1] => is
[param2] => string
)
*/
Input:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
$src = explode('/', $first);
$req = explode('/', $second);
$params = array();
for ($i = 0; $i < count($req); $i++) {
if (preg_match('!:(\w+)!', $req[$i], $matches)) {
$params[$matches[1]] = $i < count($src) ? $src[$i] : null;
}
}
print_r($params);
Output:
Array
(
[param1] => is
[param2] => string
)
精彩评论