Blackbird Blackbird - 1 year ago 85
PHP Question

Replace placeholders with dynamic data in strings with php

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!

Answer Source

Use the function strtr

$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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download