0

I needed an assistant

about replace for simple variables:

$html = '<{$headtype} class="{$class}">{$text}</{$headtype}>';
$array['headtype']  = 'h1';
$array['class']     = 'classname';
$array['text']      = 'the title'; 
// result
<h1 class="classname">the title</h1>

Knowing that the array is variable in keys and values

0

3 Answers 3

1

You can set the array key and old key to unset like that, $arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]); More information you can check below article. change the key of an array element

1

Just iterate through the array and use str_replace() to replace the strings:

foreach ($array as $key => $value) {
    $html = str_replace('{$'.$key.'}', $value, $html);
} 

Demo: https://3v4l.org/PceWI

0
$array['headtype']  = 'h1';
$array['class']     = 'classname';
$array['text']      = 'the title'; 
extract($array)
$html = '<{$headtype} class="{$class}">{$text}</{$headtype}>';

is what you want if i get the question right. please comment below and i will update my answer as you want.

5
  • 1
    This doesn't really answer the question. You still need to replace them in the string (which is what the OP actually is asking about). And if you're trying to resolve the variables inside the string, the string needs to be wrapped in double quotes. Commented Nov 25, 2017 at 18:07
  • thank you for your reply, i will update my answer in few minutes.
    – geekido
    Commented Nov 25, 2017 at 18:08
  • 1
    I would also recommend against using extract() since it clutters the variable scope and can result in unwanted results (if the scope already contains any of those variables). Commented Nov 25, 2017 at 18:10
  • 1
    Thank geekido .. Used extract( $array ); $press = preg_replace('/\{\$([a-z]+)\}/e', "$$1", $html); The result was as I wanted If you have a better code I wish you would place us for the benefit Commented Nov 25, 2017 at 18:35
  • thank you @HossamMega i've been searching, i will update when i find out better code
    – geekido
    Commented Nov 25, 2017 at 18:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.