I have a string that contains multiple templated variables like this:
$str = "Hello ${first_name} ${last_name}";
How can I do to extract these variables in an array like this :
$array = ['first_name', 'last_name'];
I have a string that contains multiple templated variables like this:
$str = "Hello ${first_name} ${last_name}";
How can I do to extract these variables in an array like this :
$array = ['first_name', 'last_name'];
Use single quotes instead of double quotes when describing the string.
$str = 'Hello ${first_name} ${last_name}';
preg_match_all('/{(.*?)}/s', $str, $output_array);
dd($output_array[1]);
[1] ?0 is the full match. 1 is the first capture group. Each index is a capture group, after the full match which is always 0. see also: php.net/manual/en/function.preg-match-all.php if you don't want to specify index you can use end()Use explode function example given below:
$str = "Hello ${first_name} ${last_name}";
$str_to_array = explode("$",$str);
$array = array();
foreach($str_to_array as $data){
if (str_contains($data, '{')) {
$array[] = str_replace("}","",str_replace("{","",$data));
}
}
print_r($array);
str_contains is for php 8You can use a simple regular expression and use preg_match_all to find all the ocurrences, like this:
<?php
$pattern = '|\${.*?}|';
$subject = 'Hello ${first_name} ${last_name}';
$matches = '';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Result:
Array
(
[0] => Array
(
[0] => ${first_name}
[1] => ${last_name}
)
)
EDIT: To get just the names of the variables, a small modification of the code will make it possible:
<?php
$pattern = '|\${(.*?)}|'; // We added parenthesis making '.*?' a sub-pattern now.
$subject = 'Hello ${first_name} ${last_name}';
$matches = '';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Result:
Array
(
[0] => Array
(
[0] => ${first_name}
[1] => ${last_name}
)
[1] => Array
(
[0] => first_name
[1] => last_name
)
)
Now the first element of the result array contains the matched results for the full regex expression, and the second one contains the matched results for the sub-pattern.