Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best practice to replace a string with html code (results from array)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading