PHP helper function to replace placeholders in string

Below is the PHP helper function which can be use to replace placeholders in a specified string with their actual values:

function replace_placeholders($text, $placeholders = []) {

$placeholderPrefix = ':';

foreach ($placeholders as $key => $value) {

$text = str_replace($placeholderPrefix.$key, $value, $text);

}

return $text;

}

Usage:

$text = 'Learn beginners, intermediate and advance level :LANGUAGE and associated technologies by :NAME.';
$placeholders = ['NAME' => 'PHP Tutors', 'LANGUAGE' => 'PHP'];
echo replace_placeholders($text, $placeholders);
//Output:
Learn beginners, intermediate and advance level PHP and associated technologies by PHP Tutors.

Description:

  • $text is the parameter containing string in which we have placeholders :LANGUAGE and :NAME in the above example.
  • $placeholders is the parameter containing placeholders as an array key and actual values as an array values.
  • Using str_replace() PHP’s function we replace placeholders with their actual values like :LANGUAGE with PHP and :NAME with PHP Tutors as shown in above example.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s