PHP replace string with values from array

2019-05-11 14:49发布

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

7条回答
一纸荒年 Trace。
2楼-- · 2019-05-11 15:22

You could use str_replace

$replacedKeys = array('<%First Name%>','<%Last Name%>');

$values = array('John','Smith');

$result = str_replace($replacedKeys,$values,$textData['text']);
查看更多
手持菜刀,她持情操
3楼-- · 2019-05-11 15:24
$array = array('<%First Name%>' => 'John', '<%Last Name%>' => 'Smith');
$result = str_replace(array_keys($array), array_values($array), $textData['text']);
查看更多
别忘想泡老子
4楼-- · 2019-05-11 15:26
echo ' Hello '.$array[0][First Name].' '.$array[0][Last Name].'  welcome';
查看更多
再贱就再见
5楼-- · 2019-05-11 15:29

Can you try this,

    $string ="Hello <%First Name%> <%Last Name%> welcome";
    preg_match_all('~<%(.*?)%>~s',$string,$datas);
    $Array = array('0' => array ('First Name' => 'John', 'Last Name' => 'Smith' ));
    $Html =$string;
    foreach($datas[1] as $value){           
        $Html =str_replace($value, $Array[0][$value], $Html);
    }
    echo str_replace(array("<%","%>"),'',$Html);
查看更多
虎瘦雄心在
6楼-- · 2019-05-11 15:44

You can use an array for both the search and replace variables in str_replace

$search = array('first_name', 'last_name');
$replace = array('John', 'Smith');

$result = str_replace($search, $replace, $string);
查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-05-11 15:44
$string = "Hello <%First Name%> <%Last Name%> welcome";
$matches = array(
    'First Name' => 'John',
    'Last Name' => 'Smith'
);

$result = preg_replace_callback('/<%(.*?)%>/', function ($preg) use ($matches) { return isset($matches[$preg[1]]) ? $matches[$preg[1]] : $preg[0]; }, $string);            

echo $result;
// Hello John Smith welcome
查看更多
登录 后发表回答