Answer the question
In order to leave comments, you need to log in
How to properly break one term based on another?
Task:
there are 2 rows
a) Lorem {val1} dolor sit {val2}, consectetur adipisicing {val3}.
b) Lorem ipsum dolor sit amet, consectetur adipisicing elit.
As you can see, the line (b) is the same line (a) in which the values were substituted into the {} blocks.
How can I get an array of the following type based on both lines:
$res = [
"{val1}" => "ipsum",
"{val2}" => "amet",
"{val3}" => "elit"
];
Answer the question
In order to leave comments, you need to log in
$mask = "Lorem {val1} dolor sit {val2}, consectetur adipisicing {val3}.";
$str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit.";
preg_match_all("/({.*?})/", $mask, $mask_matches);
$re = '/^' . preg_replace("/\\\{.*?\\\}/", '(.*?)', preg_quote($mask, '/')) . '$/';
preg_match($re, $str, $str_matches);
array_shift($str_matches);
$result = array_combine($mask_matches[1], $str_matches);
print_r($result);
Array
(
[{val1}] => ipsum
[{val2}] => amet
[{val3}] => elit
)
$str1 = 'Lorem {val1} dolor sit {val2}, consectetur adipisicing {val3}';
$str2 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit';
$words1 = explode(' ', $str1);
$words2 = explode(' ', $str2);
$items = count($words1);
$result = [];
for($i = 0; $i< $items; $i++) {
if(preg_match('/{\w*}/', $words1[$i])) {
$result["$words1[$i]"] = $words2[$i];
}
}
print_r($result);
Cut out the curly braces in the end, I think they are not needed, if they are, then $patterns[] = $m[0];
And this solution does not depend on whether the string has spaces or not.
$s1 = 'Lorem {val1} dolor sit {val2}, consectetur adipisicing {val3}.';
$s2 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.';
$patterns = [];
$pattern2 = preg_replace_callback('|\{([a-z0-9]+)\}|', function($m) use (&$patterns) {
$patterns[] = $m[1];
return '(.*)';
}, $s1);
preg_match('|' . $pattern2 . '|', $s2, $matches);
$res = array_combine($patterns, array_slice($matches, 1));
var_dump($res);
There is a lot of room for creativity here. Any programmer will only be delighted with such a task.
As an option, this solution: Split the string into substrings between "}" and "{", after turning the string into "}" + str + "{", to make it easier to process boundary options.
Then go through the resulting set, cutting out the first variant found from the second line. The remaining substrings will be the desired values
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question