skip to Main Content

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

3

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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}
            )
    
    )
    
    Login or Signup to reply.
  3. 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]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search