Please help, how they solved it? array preg_replace

$code = "<h2>Foo is [foo] and bar is [bar].</h2>";

$a['foo'] = 'bar';
$a['bar'] = 'foo'

echo preg_replace("/\\[(\\S+)\\]/e", $a["\\$\\\\1"], $code);

First way:

$code = "<h2>Foo is [foo] and bar is [bar].</h2>";

$patterns = ['/\[foo\]/', '/\[bar\]/'];
$replacements = ['bar', 'foo'];

echo preg_replace($patterns, $replacements, $code);

Second way:

$code = "<h2>Foo is [foo] and bar is [bar].</h2>";

$patterns = [
    'foo' => 'bar',
    'bar' => 'foo'
];

foreach($patterns as $pattern => $replacement){
    $code = preg_replace('/\['.$pattern.'\]/', $replacement, $code);
}

echo $code;

Thank you for second way. it replace only that elements, which declared on array. I want realize this:

$code='<!DOCTYPE HTML>
<html lang="ru">
<head>
    <meta charset="utf-8">
    <meta name="robots" content="index, follow">
    <meta name="author" content="[author]">
    <meta name="publisher" content="[Pname]">
    <meta name="description" content="[description]">
    <meta name="keywords" content="[keywords]">
    <meta name="generator" content="[generator]">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
 
<title>[title]</title>
 
</head>

<body>
 
<header>
   
</header>

[menu]
[content]
[footer]
[scripts]

</body>
</html>';

$patterns = [
 'author' => 'GlobaLlink',
'Pname' => 'GlobaLlink',
'description' => 'Preg replacement',
'keywords' => 'preg_replace, preg, reg_exp',
'generator' => 'CMS',
'title' => 'Preg replacement help',
'menu' => file_get_contents('menu.html'),
'content' => 'content',
'footer' => file_get_contents('footer.html'),
'scripts' => ('<script type="text/javascript" src="page_script.js"></script>'

];

foreach($patterns as $pattern => $replacement){
    $code = preg_replace('/\['.$pattern.'\]/', $replacement, $code);
}

echo $code;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.