Home > Backend Development > PHP Tutorial > How to Replace Variables in Strings with Values using strtr in PHP?

How to Replace Variables in Strings with Values using strtr in PHP?

Barbara Streisand
Release: 2024-11-14 15:56:02
Original
413 people have browsed it

How to Replace Variables in Strings with Values using strtr in PHP?

Replacing Variables in Strings with Values in PHP

When working with dynamic strings, it's often necessary to replace specific variables with their corresponding values. In PHP, this task can be accomplished using the strtr function.

To replace a single variable, simply specify the variable as the key in an array and the desired value as the corresponding value. For example:

$club = "Barcelona";
echo strtr($data_base[0]['body'], array('{$club}' => $club));
Copy after login

This code will output:

I am a Barcelona fan.
Copy after login
Copy after login

If you need to replace multiple variables, you can use a more complex array structure:

$vars = array(
  '{$club}'       => 'Barcelona',
  '{$tag}'        => 'sometext',
  '{$anothertag}' => 'someothertext'
);

echo strtr($data_base[0]['body'], $vars);
Copy after login

The program output will be:

I am a Barcelona fan.
Copy after login
Copy after login

Using strtr provides a concise and efficient way to replace variables in strings with their corresponding values, ensuring the accuracy and consistency of your dynamic text.

The above is the detailed content of How to Replace Variables in Strings with Values using strtr in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template