cyberfly
2/7/2018 - 5:53 AM

PHP replace placeholder with value from Object

<?php

    //usage example
    //result : 
    //https://google.com/page/nav/Ahmad/123
    //result : https://google.com/page/nav/Ali/124
    
    $list = [
      [
        'name'=>'Ahmad',
        'id'=>123
      ],
      [
        'name'=>'Ali',
        'id'=>124
      ] 
    ];
    
    $list = (obj) $list;
    
    if(!empty($list)){
      foreach($list as $item){
        $url = 'https://google.com/page/nav/{name}/{id}';
    
        $real_url = replacePlaceholderValue($url, $item)
        echo $real_url;
      }
    }
    
    //get all placeholder keys within string

    function getPlaceholderKey($placeholder)
    {
        preg_match_all('/{(.*?)}/', $placeholder, $matches);

        if (!empty($matches)) {
            return $matches[1];
        }

        return [];
    }
    
    //replace placeholder with object value
    
    function replacePlaceholderValue($string, $item)
    {
        $placeholder_list = getPlaceholderKey($string);

        if (!empty($placeholder_list)) {
            foreach ($placeholder_list as $placeholder) {
                $string = str_replace('{'.$placeholder.'}', $item->$placeholder, $string);
            }
        }

        return $string;
    }