3

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?

1
  • 1
    Even if str_replace accepted arguments like that, you can't use variables inside single quotes. Read the manual before using a function if you aren't sure what it accepts as input. Commented Nov 6, 2018 at 17:11

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.