Minggu, 13 Februari 2022

PHP String Replace All From Array

<?php
    $string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
    
    $array = array(
        '{name}' => 'Agustian Romy Ariansyah',
        '{detail.country}' => 'Indonesia',
        '{detail.age}' => '32'
    );
    
    $result = str_replace(array_keys($array), array_values($array), $string);
    
    echo $string; //My name is Agustian Romy Ariansyah. I live in Indonesia and age is 32
?>


<?php
    $string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
    
    $array = array(
        'name' => 'Agustian Romy Ariansyah',
        'detail' => array(
            'country' => 'Indonesia',
            'age' => '32'
        )
    );

    foreach($array as $key => $value) {
        if(is_array($value)) {
            foreach($value as $key2 => $value2) {
                $string = str_replace("{".$key.".".$key2."}", $value2, $string);
            }
        } else {
            $string = str_replace("{".$key."}", $value, $string);
        }
    }
    
    echo $string; //My name is Agustian Romy Ariansyah. I live in Indonesia and age is 32
?>

Tidak ada komentar: