note 53755 added to function.str-replace
| From: | mxgxw at navegante dot com dot sv | Date: | Sun, 12 Jun 2005 01:41:31 +0000 |
| Subject: | note 53755 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90281@lists.php.net to get a copy of this message | ||
Estaba buscando alguna forma de realizar sustituciones rápidas en un archivo de plantillas,
intenté usar un sistema de sustitución usando output buffer, sin embargo me vi en el inconvenente
que con los archivos XML las etiquetas <? y ?> en algunos servidores se evaluaban como php,
impidiendome usar cualquier archivo de plantillas.
Por ello diseñe un codigo utilizando str_replace que busca las ocurrencias de variables en un
archivo de plantillas y las reemplaza por el valor especificado.
La definicion de las variables se hace así:
<?php
$vars["{label1}"] = "Test1";
$vars["{label2}"] = "Test2";
?>
Y la evaluación haciendo uso de str_replace, de la siguiente manera:
<?php
function processTemplate($file,$vals) {
if(is_file($file)) {
$buffer = file_get_contents($file);
foreach($vals as $var=>$val) {
$buffer = str_replace($var,$val,$buffer);
}
return $buffer;
} else
return NULL;
}
?>
El archivo html usado:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
{label1}
{label2}
</body>
</html>
Y la respectiva salida haciendo uso de:
echo procesarPlantilla("test.htm",$vars);
Salida:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
Test1
Test2
</body>
</html>
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53755
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53755&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53755&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53755&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53755&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53755&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53755&report=yes
Search -- http://master.php.net/manage/user-notes.php