Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a variable in a string with the value in PHP?

Tags:

string

php

I have string like this in database (the actual string contains 100s of word and 10s of variable):

I am a {$club} fan 

I echo this string like this:

$club = "Barcelona"; echo $data_base[0]['body']; 

My output is I am a {$club} fan. I want I am a Barcelona fan. How can I do this?

like image 549
open source guy Avatar asked Feb 25 '13 10:02

open source guy


People also ask

How can I replace part of a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How do I replace a word in a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.

What is variable substitution PHP?

Variable substitution is a way to embed data held in a variable directly into string literals. PHP parse double-quoted (and heredoc) strings and replace variable names with the variable's value. By BrainBell. May 12, 2022.


2 Answers

Use strtr. It will translate parts of a string.

$club = "Barcelona"; echo strtr($data_base[0]['body'], array('{$club}' => $club)); 

For multiple values (demo):

$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests  $vars = array(   '{$club}'       => 'Barcelona',   '{$tag}'        => 'sometext',   '{$anothertag}' => 'someothertext' );  echo strtr($data_base[0]['body'], $vars); 

Program Output:

I am a Barcelona fan. 
like image 174
Husman Avatar answered Sep 22 '22 01:09

Husman


/**  * A function to fill the template with variables, returns filled template.  *  * @param string $template A template with variables placeholders {$variable}.  * @param array $variables A key => value store of variable names and values.  *  * @return string  */  public function replaceVariablesInTemplate($template, array $variables){   return preg_replace_callback('#{(.*?)}#',        function($match) use ($variables){             $match[1] = trim($match[1], '$');             return $variables[$match[1]];        },        ' ' . $template . ' '); } 
like image 20
tiffin joe Avatar answered Sep 20 '22 01:09

tiffin joe