Err, I’m trying to use a preg_replace to replace in a block of text, variable placeholders (of the form ‘[varname]’) with their corresponding values from an array - the array key is the variable name.
$code = "<h2>Foo is [foo] and bar is [bar].</h2>";
$a['foo'] = 'bar';
$a['bar'] = 'foo'
echo preg_replace("/\\[(\\S+)\\]/e", $a["\\$\\\\1"], $code);
That SHOULD output ‘<h2>Foo is bar and bar is foo.</h2>’ but it isn’t, it’s just showing ‘<h2>Foo is and bar is .</h2>’, which means the replacement’s not being made properly. Can anyone help, please? The preg functions rock but I hate 'em, heh.
Isn’t there an easier way to do this? I got it working once, and lost the file. I’d rather not work with the globals… don’t mean to sound ungrateful though.
Call preg_replace in a loop, instead of all at once with the callback:
$a = array('foo'=>'bar', 'bar'=>'foo');
$result = '<h2>Foo is [foo] and bar is [bar].</h2>';
foreach(array_keys($a) as $key) {
$result = preg_replace(
'/\\['.preg_quote($key,'/').'\\]/'
,$a[$key]
,$result
);
}
Im not sure if a loop with str_replace is faster then a single preg_replace. I know you can do array replacing all at once with one str_replace, but you’ll have to investigate on that yourself if you want more information on that.
I use the same thing as feti suggests which works very well. Normally I run through the arraykeys and just add the { and } to them and put them one array and use array_values to put the values into another array and use str_replace like feti does. I recon this is quicker than preg_replace myself, but I haven’t benchmarked it. However, if this code is only used occasionally to render the odd error message, why should one care about this. If you are going to optimise for speed there will probably be many other areas in an app that could be optimised which can be highlighted using a profiler.
/**
* Replace an Element of HTML Code
* @param string $Name Identification of element
* @param mixed $args String or Array of values passed in identification
* @param string $el HTML code for substitute the code between the element
* @access private
*/
function _Element_replace($Name, $args=NULL, $el=NULL)
{
if(is_array($args)){
$comp=“\s{1,}”;
foreach($args as $key=>$value)
$comp.=“$key=\”$value\“\s{0,}”;
}elseif($args!=NULL){
$comp=“\s{0,}”.$args;
$comp=preg_replace(“[\s{1,}]”,“\s{1,}”,$comp);
}
$preg="|<!-- $Name$comp(.*?)-->(.*?)<!-- end $Name -->|s";
$this->_code=preg_replace($preg,$el,$this->_code);
}