I've got strings that look like this: "[1] edited profile picture of [2]" - The numbers in brackets stand for ID's of users (saved in Database). What would be an efficient way to replace these numbers with data from the database in PHP? I should also mention, that there can be zero of these numbers as well as twenty of them in a string. Thanks in advance!
Asked
Active
Viewed 292 times
-1
-
1See [*Replacing Placeholder Variables in a String*](http://stackoverflow.com/questions/15773349/replacing-placeholder-variables-in-a-string). – Wiktor Stribiżew Nov 26 '16 at 15:29
-
Build an associative array with `'[n]'` as keys and use `strtr`. – Casimir et Hippolyte Nov 26 '16 at 15:36
1 Answers
1
Use the function strtr
<?php
$string = '[1] edited profile picture of [2]';
$replaceArray = array('[1]' => 'Mark Zuckerberg',
'[2]' => 'John doe');
$string = strtr($sting, $replaceArray);
echo $string;
?>
Gives you
Mark Zuckerberg edited profile picture of John doe

Alex Wiebogen
- 356
- 1
- 13