Reputation: 4089
I have strings that are sprinkled through a few classes making changes difficult. What I would like to do is have a config function that puts all the strings into variables and are used in the program so I only have to edit one function. (PHP)
My question is how could I have a string (or other data type) that allows me to concatinate later. For example:
$vars = array('one', 'two', 'red', 'blue');
foreach($vars as $var) {
echo "List all rows with <strong>$var</strong> in the column.<br/>";
}
List all rows with one in the column.
List all rows with two in the column.
List all rows with red in the column.
List all rows with blue in the column.
I would like to hold onto "List all rows with $var in the column." in one place and then add in the $var in another function at another time. I know I could just hold onto two variables or put it in an array but I felt like there must be some data structure that I was missing that could make this job easier.
Thank you!
Upvotes: 0
Views: 170
Reputation: 6527
<?php
$str = "blah blah blah {var}";
....
$output = str_replace("{var}",$someVar,$str);
Good sollution, @Andrej. But a tune up:
<?php
$search = array("{name}");
$replace = array($name);
$var = str_replace($search, $replace, "My name is {name}");
Upvotes: 2
Reputation: 32252
Read up on printf()
, you don't have to worry about variable naming.
$string = "List all rows with <strong>%s</strong> in the column.<br/>";
$var = "herp";
printf($string, $var);
function something() {
$something_else = 'derp';
printf($string, $something_else);
}
something();
Upvotes: 1
Reputation: 674
$str = "blah blah blah {var}";
....
$output = str_replace("{var}",$someVar,$str);
Read about templaters.
Upvotes: 1