str_replace() with associative array

✔ Recommended Answer

$text = strtr($text, $array_from_to)

By the way, that is still a one dimensional "array."

Source: stackoverflow.com

Answered By: Matthew

Method #2

In PHP, you can use str_replace with an associative array by using array_keys and array_values to generate two separate arrays for the keys and values of the associative array. Here's an example:

php
$search = array( '{first_name}', '{last_name}', '{age}' ); $replace = array( 'John', 'Doe', '30' ); $text = "Hello {first_name} {last_name}, you are {age} years old."; $result = str_replace(array_keys($search), array_values($replace), $text); echo $result;

In this example, we first create an associative array $search where the keys are the search strings (placeholders) and the values are the replacement strings. We also create an array $replace with the corresponding replacement values for each search string.

To use str_replace with this associative array, we use array_keys($search) to extract the keys (search strings) and array_values($replace) to extract the values (replacement strings) into separate arrays. We then pass these arrays to str_replace as the first and second parameters, respectively.

The resulting string will be "Hello John Doe, you are 30 years old." as before. Note that this approach assumes that the keys in the associative array are unique and match exactly with the search strings in the input string.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755