Home > Back-end >  Best practice to replace a string with html code (results from array)
Best practice to replace a string with html code (results from array)

Time:06-30

Given a string like this...

$htmlPattern = "User name is: #name# and user company is #company#";

How do I replace the substrings #name# and #company# with elements from variables?

For example if $name is "John" and $company is Microsoft, how can I produce the string User name is: John and user company is: Microsoft?

CodePudding user response:

Change the array so that the keys include # around them. Then you can use this as the replacement argument with strtr().

$myArr = [
    ["#name#" => "John", "#company#" => "Microsoft"],
    ["#name#" => "Erica", "#company#" => "Apple"]
];

foreach ($myArr as $row) {
    $emptyHtml  .= strtr($htmlPattern, $row)
}

CodePudding user response:

you can use multiple str_replace inside each other like this:

<?php

$name = "jhon";
$company = "microsoft";

$htmlPattern = "<div>User name is: #name# and user company is #company#</div>";
 
$res = str_replace("#name#",$name,str_replace("#company#",$company,$htmlPattern));

print($res);


?>
  •  Tags:  
  • php
  • Related