Blackbird Blackbird - 6 days ago 6
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

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
Comments