Reputation: 495
I want to dynamically replace placeholder variables in a string.
str_replace("\$", $data["Whatever follows the \$], $variable);
\$
signifies a placeholder variable, \$ID
for example.
The data I want it to be replace with is in an array. $\ID
should be replaced with $data['ID']
.
For example, if I have a string that says "The ID is \$ID
and name is \$name
". I want to replace both the \$ID and \$name with the relevant data in my $data
object. $\ID
would be $data['ID']
and so on.
This needs to be dynamic. I don't want to hard code it to replace \$ID
with $data['ID']
. The key used to get the data in $data should be equal to what follows the \$
.
I'm having trouble figuring out not only how to do this dynamically like I have talked about, but to do it for every \$
in a string.
Upvotes: 0
Views: 2263
Reputation: 12375
This will do the job for you! https://3v4l.org/XRQii
<?php
$string = 'The ID is \$ID and name is \$name';
$row = [
'ID'=> 5,
'name' => 'delboy1978uk',
];
function replaceStuff($string, $row) {
preg_match_all('#\\$\w+#', $string, $matches);
foreach ($matches[0] as $match) {
$key = str_replace('$', '', $match);
$replace = '\\'.$match;
$string = str_replace($replace, $row[$key], $string);
}
return $string;
}
echo replaceStuff($string, $row);
See http://php.net/manual/en/function.preg-match-all.php for more info on preg_match_all()
.
Upvotes: 0
Reputation: 771
Try this:
$string = 'some $ID $PARAM string';
$values = array("ID" => "idparam", "PARAM" => "p");
preg_match_all("/\\\$(?<name>[a-zA-Z0-9]+)/", $string, $matches);
foreach($matches["name"] as $m) {
if(!isset($values[$m])) {
//TODO handling
continue;
}
$string = str_replace('$'.$m, $values[$m], $string);
}
var_dump($string);
The keys in $values
should be name of the parameter without the dollar sign.
Upvotes: 0
Reputation: 3074
Use printf() or sprintf().
If you mark your placeholder with a number, you can repeat it any number of times in your string.
sprintf("This is my test string. Here's a placeholder: %1$s, and a another: %2$s, First one again: %1$s", $var1, $var2);
Upvotes: 1