str_replace to replace mutliple string - php & laravel

Viewed 2539

I want to replace multiple strings in my tutorial app. This is what i have now but it doesn't work as wanted.

Controller

public function replaceStrings()
{
      $data = 13; 
      $age = 11; 
      $cod = 45;
      $test = "My data is %data%, My age is %age%, My cod is %cod%";          
      $new_message =  str_replace('%data%',$data,'%age%','$age','%cod%','$cod', $text); 
      return $new_message;          
}

I am expecting the function to return "My data is 13, My age is 11, My age is 45".

How do i get this done please?

2 Answers

You have to do them as arrays:

  $replace = [
     '%data%' => 13, 
     '%age%' => 11, 
     '%cod%' => 45
  ];
  $test = "My data is %data%, My age is %age%, My cod is %cod%";          
  $new_message =  str_replace(array_keys($replace), $replace, $text); 
  return $new_message;    

You can use 2 arrays, but I prefer using one as it keeps everything nicely lined up.

Cheers.

I would suggest to rather use sprintf() for that.

Working example:

    $data = 13; 
    $age = 11; 
    $cod = 45;

    $text = "My data is %s, My age is %s, My cod is %s";
    $new_message =  sprintf($text, $data, $age, $cod);
Related