Home > Back-end >  Laravel 8 how to parse template variables in string
Laravel 8 how to parse template variables in string

Time:01-05

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'];

CodePudding user response:

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]);

CodePudding user response:

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);

CodePudding user response:

You 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}
        )

)
  • Related