Home  >  Q&A  >  body text

Top-level method to replace a string with HTML code (generated from an array)

Given a string like this...

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

How to replace the substrings #name# and #company# with elements in a variable?

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

P粉596161915P粉596161915154 days ago350

reply all(2)I'll reply

  • P粉029057928

    P粉0290579282024-04-07 11:53:08

    You can use multiple str_replaces inside each other like this:

    User name is: #name# and user company is #company#
    "; $res = str_replace("#name#",$name,str_replace("#company#",$company,$htmlPattern)); print($res); ?>

    reply
    0
  • P粉311617763

    P粉3116177632024-04-07 11:21:21

    Change the array so that it contains # around the keys. You can then use it as strtr().

    $myArr = [
        ["#name#" => "John", "#company#" => "Microsoft"],
        ["#name#" => "Erica", "#company#" => "Apple"]
    ];
    
    foreach ($myArr as $row) {
        $emptyHtml  .= strtr($htmlPattern, $row)
    }

    reply
    0
  • Cancelreply