Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace string with values from array

I have a string such as:

   Hello <%First Name%> <%Last Name%> welcome

and I have a array

 [0] => Array
    (
        [First Name] => John
        [Last Name] => Smith
    )

What I need to do is take the string and replace the words in <% with the actual text from the array

So my output would be

   Hello John Smith welcome

Im not sure how to accomplish this but I cant even seem to replace it with regular text

$test = str_replace("<%.*%>","test",$textData['text']);

Sorry I should of mentioned that the array keys may vary as well as the <%First Name%>

so it could even be <%city%> and the array can be city=>New York

like image 588
Yeak Avatar asked Jan 13 '14 19:01

Yeak


People also ask

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

What is the use of Str_replace in PHP?

Definition and Usage The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

Which of the following is the use of strpos () function in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.


1 Answers

$array = array('<%First Name%>' => 'John', '<%Last Name%>' => 'Smith');
$result = str_replace(array_keys($array), array_values($array), $textData['text']);
like image 87
Aron Cederholm Avatar answered Nov 15 '22 04:11

Aron Cederholm